如何解决盒子塌陷?

220 阅读2分钟

今天有人问这个问题, 如何解决盒子塌陷? 我不知道什么是盒子塌陷,搜了一下,发现可能是说 margins callapose的问题。 如下所示:

<body>
    <div class="boxOutter">
        <div class="boxInner"></div>
    </div>
</body>
*{
    margin: 0;
    padding: 0;
}

.boxOutter{
    width: 200px;
    height: 200px;
    background-color: aqua;

}
.boxInner{
  display: flex;
    width: 100px;
    height: 100px;
  background-color: blue;
  margin-top: 50px;
}

效果: 内部div的margin 变成了外部div的margin, 如下图:

image.png

完整代码 GmQpOhbs - 码上掘金 (juejin.cn)

然后读了一下文档:

Adjoining vertical margins collapse, except:

Margins of the root element's box do not collapse. If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block. Horizontal margins never collapse.

Two margins are adjoining if and only if:

both belong to in-flow block-level boxes that participate in the same block formatting context no line boxes, no clearance, no padding and no border separate them (Note that certain zero-height line boxes (see 9.4.2) are ignored for this purpose.) both belong to vertically-adjacent box edges, i.e. form one of the following pairs: top margin of a box and top margin of its first in-flow child bottom margin of box and top margin of its next in-flow following sibling bottom margin of a last in-flow child and bottom margin of its parent if the parent has 'auto' computed height top and bottom margins of a box that does not establish a new block formatting context and that has zero computed 'min-height', zero or 'auto' computed 'height', and no in-flow children A collapsed margin is considered adjoining to another margin if any of its component margins is adjoining to that margin.

9.4.1 Block formatting contexts Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.

www.w3.org/TR/CSS2/box…

The margins of adjacent flex items do not collapse.
www.w3.org/TR/css-flex…

As adjacent grid items are independently contained within the containing block formed by their grid areas, the margins of adjacent grid items do not collapse.
www.w3.org/TR/css-grid…

总结: 解决"盒子塌陷"的方法大概有三种: 1, 隔开margin, 不管用什么东西, 2, 创建新的BFC, 3, 使用flex 或者grid