通常,在CSS中,当父级及其最后一个子级具有边距时,边距会折叠以创建单个边距.例如
article {
margin-bottom: 20px
}
main {
background: pink;
margin-bottom: 20px;
}
footer {
background: skyblue;
}Run Code Online (Sandbox Code Playgroud)
<div id="container">
<main>
<article>
Item 1
</article>
<article>
Item 2
</article>
</main>
<footer>Footer</footer>
</div>Run Code Online (Sandbox Code Playgroud)
如您所见,即使在标签和标签20px上都指定了边距,您也只能在最后一个文章和页脚之间获得边距.articlemain20px
但是,当使用flexbox时,我们40px在最后一篇文章和页脚之间得到一个边距- 20p从文章到主页的整个x边距,以及20px从主页面到页脚的另一个边距.
#container {
display: flex;
flex-direction: column;
}
article {
margin-bottom: 20px
}
main {
background: pink;
margin-bottom: 20px;
}
footer {
background: skyblue;
}Run Code Online (Sandbox Code Playgroud)
<div id="container">
<main>
<article>
Item 1
</article>
<article>
Item 2
</article>
</main>
<footer>Footer</footer>
</div>Run Code Online (Sandbox Code Playgroud)
有没有办法让flexbox边距的行为与非flexbox边缘的行为相同?
Mic*_*l_B 62
边距折叠是块格式化上下文的一个特征.
在flex格式化上下文中没有边距折叠.
3. Flex Containers:
flex和inline-flexdisplay值Flex容器为其内容建立新的flex格式上下文.这与建立块格式化上下文相同,除了使用flex布局而不是块布局.例如,浮动不会侵入Flex容器,并且Flex容器的边距不会随其内容的边距而折叠.
ori*_*dam 25
尽管使用 Flexbox 无法实现边距折叠,但您可以使用它gap来实现相同的结果:
.parent {
display: flex;
flex-wrap: wrap;
flex-direction: row;
column-gap: 5px;
row-gap: 15px;
max-width: 70px;
outline: 1px solid #440;
}
.parent > div {
background: #8ff;
width: 20px;
height: 20px;
}Run Code Online (Sandbox Code Playgroud)
<div class="parent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>Run Code Online (Sandbox Code Playgroud)
https://coryrylan.com/blog/css-gap-space-with-flexbox
注意:这不是一种使边距在弹性框布局中的行为方式与在块布局中相同的方法;然而,在某些情况下,这可能有助于解决保证金问题。
您可以使用伪选择器来获得您想要的效果,而不是依靠折叠边距:
main{
display: flex;
flex-direction: column;
margin-bottom: 20px;
}
article{
margin-bottom: 20px;
background: #eee;
}
article:last-child{
margin-bottom: 0;
}
footer{
background: #eef;
}Run Code Online (Sandbox Code Playgroud)
<main>
<article>
This is article number 1
</article>
<article>
This is article number 2
</article>
<article>
This is article number 3
</article>
</main>
<footer>
This is the footer of the page
</footer>Run Code Online (Sandbox Code Playgroud)