为什么 float collapse 不会出现 fixed position

why float collapse does not arise with fixed position

我玩花车,然后我注意到 "float collapse bug" 不会出现固定位置。这里是 example.

所以我有两个 divs:

<body
    <div class="static">
        <img>
        <p>text text text</p>
    </div>
    <div class="fixed">
        <img>
        <p>text text text</p>
    </div>
</body>

第一个是静态位置,第二个是固定位置:

.fixed, .static{
    outline: 1px solid black;
    width: 150px;
}
.fixed{
    position: fixed;
    left: 200px;
    top: 200px;
}
img{
   float: right;
   background-color: green;
   width: 100px;
   height: 100px;
}

结果:

那么为什么第二个 fixed-div 不需要 .clearfix 之类的东西来修复浮动崩溃?

因为 position: fixed; 创建 Block formatting context.

也试试下面的样式,它们在您的 div.

中有类似的效果
  • float
  • position absolutefixed
  • display - inline-blocks, table, table-cells
  • overflow - hidden, auto

如果你想让它们看起来一样,你可以输入 overflow-y:hidden;

https://jsfiddle.net/1nq8b7xs/3/

或者如果您希望它们并排出现,请使用 display:inline-block 并从您的固定 class

中删除位置固定

https://jsfiddle.net/1nq8b7xs/4/

.fixed, .static{
    outline: 1px solid black;
    width: 150px;
    overflow-y:hidden;  /*added this*/
}
.fixed{
    left: 200px;
    top: 200px;
}
img{
   float: right;
   background-color: green;
   width: 100px;
   height: 100px;
}
.fixed, .static{display:inline-block;}
<body>
    <div class="static">
        <img>
        <p>text text text</p>
    </div>
    <div class="fixed">
        <img>
        <p>text text text</p>
    </div>
</body>