具有以下 HTML
<div class="child-of-body">
This is a text
</div>
和下面的 CSS
.child-of-body {
position: absolute;
top: 10%;
}
我可以设置所选元素的 top
值。
我看到 10%
是根据父高度计算的。
如何根据父宽度设置 top
属性的百分比值?
我知道这可以通过 JavaScript 实现,但仅使用 CSS 是否可行?
最佳答案
我认为您正在寻找 margin-top
属性。
顶部/底部 padding
或 margins
的百分比值是相对于包含 block 的 width
的。
.child-of-body {
position: absolute;
margin-top: 10%;
}
此外,Louis Lazaris 的 Vertical Percentages in CSS 值得一看。 文章。
关于javascript - 根据父宽度定位绝对顶部属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21434053/