【问题标题】:Centering by aboslute position works vertically, but not horizontaly [duplicate]以绝对位置为中心在垂直方向上有效,但在水平方向上无效[重复]
【发布时间】: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 规范。在那里的某个地方应该详细说明宽度、高度和位置“边缘”之间的关系,以及在解决冲突时哪些是“较弱”的。

标签: html css centering


【解决方案1】:

因为 margin 你给盒子 blue margin left right bottom and top 100px

而且你不给盒子橙色只是保证金自动是平均 0

所以如果我在框橙色边距中给边距和相同高度的框蓝色像这样

<div id="vertical" class="wrapper">
        <div class="centered" style="
    margin: 40px  0;
">
        </div>
      </div>

盒子橙色可以是中心

【讨论】:

  • 但为什么 ?如果你使用 flexbox 你可以很容易
猜你喜欢
  • 2012-04-20
  • 2012-12-27
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多