javascript - 根据父宽度定位绝对顶部属性

标签 javascript html css

具有以下 HTML

<div class="child-of-body">
    This is a text
</div>

和下面的 CSS

.child-of-body {
    position: absolute;
    top: 10%;
}

我可以设置所选元素的 top 值。 我看到 10% 是根据父高度计算的。

如何根据父宽度设置 top 属性的百分比值?

我知道这可以通过 JavaScript 实现,但仅使用 CSS 是否可行?

JSFIDDLE

最佳答案

我认为您正在寻找 margin-top 属性。

顶部/底部 paddingmargins 的百分比值是相对于包含 block 的 width 的。

.child-of-body {
    position: absolute;
    margin-top: 10%;
}

JSFiddle Demo .

此外,Louis Lazaris 的 Vertical Percentages in CSS 值得一看。 文章。

关于javascript - 根据父宽度定位绝对顶部属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21434053/

相关文章:

javascript - 必应 map : how to set zoom level so pinpoint is visible to users current location

javascript - setTimeout 不会产生正确的异步行为

php - html 中的奇怪 PHP

css - 如何自动调整一个div?

css - chrome 缓存 bootstrap css 吗?

javascript - 表单提交后运行脚本和php

javascript - 运行 setInterval 函数,停止 3 秒然后继续运行

html - 为什么文本不会显示在 html 中

javascript - 如何创建 anchor ,添加 'onclick' 函数并转换为字符串

html - 使用 Bootstrap 在图标(glyph/font-awesome)旁边居中多行