css - 左边距在溢出时不起作用 :auto element following the float

标签 css css-float overflow

我目前正在尝试创建一个两列布局,其中左列 float ,右列通过形成新的 block 格式化上下文来限制 float 。这样可行。后来,我尝试在左列和右列内容之间放置一些可见的空间。如果我在右列上设置左填充,它就会起作用。我还尝试用右列的左边距替换左边距,并认为它们会产生相同的效果。然而,令我惊讶的是,左边距根本不起作用

我用下面的代码重现了这个问题。请注意,在中间的示例中,在右列上设置左边距并没有真正将其推离左列

* {
  margin: 0;
  padding: 0;
}

.container {
  height: 50px;
  line-height: 50px;
  width: 500px;
}

.container + .container {
  margin-top: 20px
}

.left {
  float: left;
  width: 150px;
  height: 100%;
  background: orange;
  text-align: center;
}

.right {
  overflow: auto;
  background: skyblue;
  height: 100%;
}

.with-padding {
  padding-left: 30px;
}

.with-margin {
  margin-left: 30px;
}
<div class="container">
  <div class="left">left column, floated</div>
  <div class="right with-padding">
    <p>left padding works</p>
  </div>
</div>

<div class="container">
  <div class="left">left column, floated</div>
  <div class="right with-margin">
    <p>left margin dost not work</p>
  </div>
</div>

<div class="container">
  <div class="left">left column, floated</div>
  <div class="right">
    <div class="with-margin">
      <p>left margin works on the wrapper div</p>
    </div>
  </div>
</div>

我确实在互联网上搜索过这个主题,但没有找到太多相关信息。我怀疑这可能与 block 格式化上下文(BFC)的概念有关。如果我理解正确的话,margin 表示目标框的外边缘和包含 BFC 的内边框之间的距离。

如果我们在一个本身形成自己的 BFC 的盒子上设置边距,那么边距不应该起作用吗?因此,在第三个示例中,我将文本放入额外的包装器中,并在该包装器上设置边距,看起来左边距再次起作用。不过,这只是我的猜测。

最佳答案

这里的关键点是

The border box of ... an element in the normal flow that establishes a new block formatting context (such as an element with overflow other than visible) must not overlap the margin box of any floats ...

CSS 2.2 Section 9.5 Floats

因此,此类 BFC 的位于边框外部的边距可以(在第二种情况下)与 float 重叠,但位于边框内部的填充则不能。

关于css - 左边距在溢出时不起作用 :auto element following the float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68583524/

相关文章:

html - <ul> <li> 居中,不向下移动..不确定为什么/如何修复

css - 总是一个左浮动列表元素与 css

html - 为什么纯百分比包装器不起作用?

html - 在html中更改对 Angular 渐变线两侧的文本颜色

javascript - 根据条件锁定和解锁

html - 在保持单独的行的同时在左侧和右侧 float div

css - 反向重用 CSS 动画(通过重置状态?)

assembly - 如何在 mips 程序集中打印大于 32 位的数字?

HTML/CSS : Why is body not stretching to its contents?

html - 如果 DIV 内容太大,则保持 DIV 并排并使页面可水平滚动