【发布时间】:2023-02-21 00:31:30
【问题描述】:
有人能给我解释一下,为什么horizontalwrapper 中的.centered div 居中而vertical 中的不是?即使应用相同的原则?
它们都有绝对定位,都从边缘有 zeores,相对于它们应该居中,并且都有 margin: auto。然而,一个是居中的,另一个不是。
.wrapper {
margin: 100px;
background: lightblue;
position: relative;
}
#vertical {
width: 20px;
height: 100px;
}
#horizontal {
height: 20px;
width: 100px;
}
.centered {
position: absolute;
background: orange;
margin: auto;
}
#horizontal .centered {
height: 60px;
width: 20px;
top: 0;
bottom: 0;
}
#vertical .centered {
width: 60px;
height: 20px;
left: 0;
right: 0;
}
<div id="horizontal" class="wrapper">
<div class="centered">
</div>
</div>
<div id="vertical" class="wrapper">
<div class="centered">
</div>
</div>
【问题讨论】:
-
你看过弹性盒子吗?绝对定位是我很少使用的东西;它适用于非常小众的应用程序。一般来说,如果你是居中的东西,你只需要 flexbox。 css-tricks.com/snippets/css/a-guide-to-flexbox
-
您可能需要深入研究 CSS 规范。在那里的某个地方应该详细说明宽度、高度和位置“边缘”之间的关系,以及在解决冲突时哪些是“较弱”的。