我从CSS和flexbox开始,我已经阅读了关于保证金崩溃的信息.我已经读过Bootstrap,例如避免它(我理解并同意它),但我希望边缘在特定情况下崩溃(你可以在上面的CodePen中看到).这是一系列标签,顶部和底部有20px的边距.当换行时,边距不会折叠,所以在两行标签之间我得到40px,但我想要与底部或顶部相同.
为什么利润不会崩溃,解决这个问题的最佳方法是什么?谢谢.
这是 CodePen.
这是HTML:
<main>
<div class="main-wrapper">
<div class="tags">
<ul>
<li>
<a href="#">ELEMENT 1</a>
</li>
<li>
<a href="#">ELEMENT 2</a>
</li>
<li>
<a href="#">ELEMENT 3</a>
</li>
<li>
<a href="#">ELEMENT 4</a>
</li>
<li>
<a href="#">ELEMENT 5</a>
</li>
</ul>
</div>
</div>
</main>
Run Code Online (Sandbox Code Playgroud)
这是CSS:
$red: #FC575E;
$dark-grey: #3A4250;
$medium-grey: #e6e6e6;
$white: #FFFFFF;
$light-grey: #F1F4F5;
$width: 800px;
ul {
list-style-type: none;
padding-left: 0px;
}
a {
text-decoration: none;
}
main {
background-color: $light-grey;
padding: 30px 0px;
}
.main-wrapper {
max-width: $width;
margin: auto;
}
.tags {
ul {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
margin: 0;
}
li {
margin: 20px 10px;
}
a {
display: block;
justify-content: center;
color: $dark-grey;
background-color: $medium-grey;
border-radius: 20px;
padding: 7px 20px;
transition: background-color 0.3s ease, color 0.3s ease;
}
a:hover {
color: $white;
background-color: $red;
transition: background-color 0.3s ease, color 0.3s ease;
}
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*ker 12
Flex项目的边距不会崩溃.当flex项目换行时,它们会创建自己的行,并且flex项目上的各个边距不会在行之间折叠.只有正常的,相邻的块元素堆叠在一起才会使您的预期方式崩溃.这是一个很好的参考 - https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
您可以通过去除上边距创建相同布局li
的,使一个padding-top
在ul
代替,那么只有底部边缘将之间施加li
的柔性包装一行时.
ul {
list-style-type: none;
padding-left: 0px;
}
a {
text-decoration: none;
}
main {
background-color: #F1F4F5;
padding: 30px 0px;
}
.main-wrapper {
max-width: 800px;
margin: auto;
}
.tags ul {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
margin: 0;
padding-top: 20px;
}
.tags li {
margin: 0 10px 20px;
display: block;
}
.tags a {
display: block;
justify-content: center;
color: #3A4250;
background-color: #e6e6e6;
border-radius: 20px;
padding: 7px 20px;
transition: background-color 0.3s ease, color 0.3s ease;
}
.tags a:hover {
color: #FFFFFF;
background-color: #FC575E;
transition: background-color 0.3s ease, color 0.3s ease;
}
Run Code Online (Sandbox Code Playgroud)
<main>
<div class="main-wrapper">
<div class="tags">
<ul>
<li>
<a href="#">ELEMENT 1</a>
</li>
<li>
<a href="#">ELEMENT 2</a>
</li>
<li>
<a href="#">ELEMENT 3</a>
</li>
<li>
<a href="#">ELEMENT 4</a>
</li>
<li>
<a href="#">ELEMENT 5</a>
</li>
</ul>
</div>
</div>
</main>
Run Code Online (Sandbox Code Playgroud)