html - 为什么 "position: absolute; left: 0; right: 0; width: XYpx; margin: 0 auto"实际上居中?

标签 html css

我在 CSS 方面非常精通,但今天我偶然发现了一个让我头疼的片段(herehere)。

我从没想过可以通过 margin: 0 auto 将绝对定位的元素居中,但考虑到所讨论的元素具有设置的宽度并且有 left: 0对:0,它实际上似乎有效:

#parent
{
    background: #999;
    height: 300px;
    position: relative;
    width: 300px;
}

#child
{
    background: #333;
    height: 50px;
    left: 0;
    margin: 0 auto;
    position: absolute;
    right: 0;
    width: 50px;
}
<div id="parent">
    <div id="child"></div>
</div>

( JSFiddle )

我一直认为 left: 0right: 0 将决定元素的宽度(它的第一个相对定位父元素的 100%)但看起来 width 在这里优先,因此使 margin: 0 auto 起作用。

这是定义的行为吗?我可以在任何规范中找到有关它的信息吗?我在谷歌上搜索了一下,但没有找到任何有用的信息。

最佳答案

这在 section 10.3.7 中说明了CSS2.1 规范:

The constraint that determines the used values for these elements is:

'left' + 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' + 'right' = width of containing block

如果三个都不是'auto':如果'margin-left'和'margin-right'都是'auto',在两个边距取相等值的额外约束下求解方程[。 ..]

如您所见,如果 leftright 偏移量以及 width 不是自动的。

有趣的是,仅适用于绝对定位的元素,this applies to top, height and bottom as well ,这实质上意味着可以使用自动边距使绝对定位的元素垂直居中。同样,前提是上面的三个属性不是自动的,并且各自的边距是自动的。 (在您的情况下,这意味着 margin: auto 而不是 margin: 0 auto 因为后者将垂直边距归零。)

关于html - 为什么 "position: absolute; left: 0; right: 0; width: XYpx; margin: 0 auto"实际上居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29261595/

相关文章:

html - 微信不会重定向到 iPhone 上的 iTunes 应用商店

javascript - Google 跟踪代码管理器在我的页面底部创建空按钮

html - HTML/CSS 中的播放按钮对齐问题

html - 如何为 Bootstrap 表类 'table table-bordered ' 自定义 css?它不适合我

html - CSS float right 不适用于 Firefox 和图像调整大小

javascript - 为什么 if/then 对于 document.querySelector 不起作用?剪刀石头布游戏的部分代码

jquery - 在调用另一个函数之前执行一些函数

HTML 列表元素从上到下,然后从左到右

css - 选定的文本背景颜色

html - 有没有办法将一些 <div> 标签分成两列?