我正在尝试按百分比创建垂直定位的DIV.我有父容器设置为相对,内容div设置为绝对.当我使用像素定位内容div时,这可以正常工作,但是当我尝试百分比时,百分比被忽略:
.container {
position: relative;
}
.content {
position: absolute;
left: 10%;
top: 50%;
}
<div class="container"><div class="content"> This is the content div. It should be 10% from the left of the container div.
</div></div>
Run Code Online (Sandbox Code Playgroud)
内容div显示在页面顶部,忽略50%的垂直位置.我错过了什么?提前致谢!
Jam*_*xon 25
绝对定位的元素从文档的自然流动中取出,这意味着您的容器的高度和宽度为零.
零高度和宽度的10%和50%当然是零.
如果您为容器提供高度和宽度,您的百分比位置将根据需要开始工作.
.container { position: relative; width:500px; height:500px; }
Run Code Online (Sandbox Code Playgroud)
Welp,我在SE的第一篇文章.对于那些将来看到这一点的人,您实际上可以使用视口高度作为百分比的度量.
.container {
position: relative;
top: 10vh; // 10% of height from top of div
}
Run Code Online (Sandbox Code Playgroud)