gpt4 book ai didi

css - flexbox 中的边距折叠

转载 作者:行者123 更新时间:2023-11-28 19:25:00 24 4
gpt4 key购买 nike

通常,在 CSS 中,当父级及其最后一个子级有边距时,边距会折叠以创建单个边距。例如

article {
margin-bottom: 20px
}

main {
background: pink;
margin-bottom: 20px;
}

footer {
background: skyblue;
}
<div id="container">
<main>
<article>
Item 1
</article>
<article>
Item 2
</article>
</main>
<footer>Footer</footer>
</div>

如您所见,即使在 articlemain 标签上指定了 20px 的边距,您也只会得到一个最后一个文章页脚之间的20px边距。

然而,当使用 flexbox 时,我们在最后一个 articlefooter 之间得到一个 40px 边距——一个从文章到主体的完整 20px 边距,从主体到 页脚 的另一个 20px

#container {
display: flex;
flex-direction: column;
}

article {
margin-bottom: 20px
}

main {
background: pink;
margin-bottom: 20px;
}

footer {
background: skyblue;
}
<div id="container">
<main>
<article>
Item 1
</article>
<article>
Item 2
</article>
</main>
<footer>Footer</footer>
</div>

有没有办法让 flexbox 的边距和非 flexbox 的一样?

最佳答案

边距折叠是 block formatting context 的一个特征.

flex formatting context 中没有边距崩溃.

3. Flex Containers: the flex and inline-flex display values

A flex container establishes a new flex formatting context for its contents. This is the same as establishing a block formatting context, except that flex layout is used instead of block layout. For example, floats do not intrude into the flex container, and the flex container’s margins do not collapse with the margins of its contents.

关于css - flexbox 中的边距折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com