body {
background: #8E2800;
}
#main {
background: purple;
position: relative;
color: white;
}
#title {
background: grey;
position: absolute;
top: 50%;
left: 50%;
height: 40%;
width: 50%;
}Run Code Online (Sandbox Code Playgroud)
<div>
<div id="main">
<div id="title">
<h2>Weather Forecast</h2>
</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
也可以在 codepen 上找到工作演示:http ://codepen.io/manzur/pen/RomyjK?editors=1100
position: absolute 相对于最近定位祖先的边缘的位置。
#mainhasposition: relative所以它是#title相对于定位的元素。
#main没有内容这是在正常流动(唯一的内容被绝对定位),并且它具有height的auto(默认值)。因此计算出的高度为0。
50%的0是0。
您需要相对于别的任何位置(例如通过移除视position: relative距离#main)或给予#main一定高度(通过添加内容或使用该height属性)。