html - 意外的 CSS 行为?

标签 html css

在尝试使用没有 parent 高度的容器的整个高度的分隔线时,我偶然发现了以下情况。谁能弄清楚为什么将分隔线设置为 position:absolutedisplay:inline-block 不会导致它们像预期的那样一直 float 到父容器的左侧?为什么它们实际上是内联的?

HTML

<div class="wrapper">
  <div class="box"></div>
  <div class="divider"></div>
  <div class="box"></div>
  <div class="divider"></div>
  <div class="box"></div>
</div>

CSS

.wrapper{
  width:100%;
  text-align:center;
  position: relative;
}

.box{
  display: inline-block;
  width: 150px;
  height: 100px;
  background: red;
  margin: 0 0 0 5px;
}

.divider{
  display: inline-block;
  position: absolute;
  top: 0;
  bottom: 0;
  width: 1px;
  background: black;
}

JSFIDDLE

最佳答案

那是因为 leftright 都是 auto

然后,根据§10.3.7 ,

[If] 'left' and 'right' are 'auto' and 'width' is not 'auto', then if the 'direction' property of the element establishing the static-position] containing block is 'ltr' set 'left' to the static position, otherwise set 'right' to the static-position. Then solve for 'left' (if 'direction is 'rtl') or 'right' (if 'direction' is 'ltr').

其中静态位置定义为

The static position for 'left' is the distance from the left edge of the containing block to the left margin edge of a hypothetical box that would have been the first box of the element if its 'position' property had been 'static' and 'float' had been 'none'.

如果你不想这样,指定一个值:

.divider {
  left: 0;
}

关于html - 意外的 CSS 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31352548/

相关文章:

Javascript:如何使用 ajax 请求在 for 循环内以正确的顺序将对象插入数组

javascript - 如何在 Firefox 中将多个选项传递给 bootstrap carousel 的 optional 对象?

css - 如何为我的网站删除 'Optimize CSS Delivery' 消息。

html - 缩放时重叠 Div(html、css 动画)

html - 水平导航中的所有元素都在同一高度

javascript - 如何以编程方式(在 JavaScript 中)将 "sub-divs"添加到 div?

python - 如何修复 HTML 电子邮件编号列表导致列表后的选项卡超过 99?

html - 如何向屏幕阅读器表明内容是可内联编辑的?

javascript - 无法获取图像高度,改为获取naturalHeight

html - 如果容器可滚动,如何将元素粘贴到其容器底部?