问题
here is the codepen
I want to add vertical spacing ONLY to elements between line 1 and line 2. Alternatively, only to between line 1 and line 2, and line 2 and line 3.
The flex items are random, so the amount, size of each, is dynamic.
I cannot add margins to all, because that would ruin the layout in case there is no second row at all.
HTML
<div class="flexContainer">
<div class="flexItem">a a a aaaaaaa a ax</div>
<div class="flexItem">bbbx</div>
<div class="flexItem">c c c c c cx</div>
<div class="flexItem">note: random amount of flex items</div>
<div class="flexItem">amount can very...</div>
</div>
<br/><br/><br/>
<div class="flexContainer">
<div class="flexItem">a a a aaaaaaa a ax</div>
<div class="flexItem">bbbx</div>
<div class="flexItem">c c c c c cx</div>
</div>
CSS
.flexContainer{
background-color: salmon;
display: flex;
flex-direction: row;
width: 300px;
flex-wrap: wrap;
}
.flexItem{
background-color: lightblue;
margin: 5px;
}
Browsersupport: only newest cutting edge browsers are supported.
回答1:
You can
- Add some
margin-bottom
to the first and last.flex-item
s. - Align all flex items to top with
align-items: flex-start
oralign-self: flex-start
. - Add a negative
margin-bottom
to.flexContainer
in order to counteract the margin after the last line. - Place the
.flexContainer
inside a wrapper withoverflow: hidden
.
.wrapper {
overflow: hidden;
}
.flexContainer {
background-color: salmon;
display: flex;
flex-flow: row wrap;
width: 300px;
margin-bottom: -20px; /* 25-20 = 5 */
}
.flexItem {
background-color: lightblue;
margin: 5px;
align-self: flex-start;
}
.flexItem:first-child, .flexItem:last-child {
margin-bottom: 25px;
}
<div class="wrapper">
<div class="flexContainer">
<div class="flexItem">a a a aaaaaaa a ax</div>
<div class="flexItem">bbbx</div>
<div class="flexItem">c c c c c cx</div>
<div class="flexItem">note: random amount of flex items</div>
<div class="flexItem">amount can very...</div>
</div>
</div>
<br/><br/>
<div class="wrapper">
<div class="flexContainer">
<div class="flexItem">a a a aaaaaaa a ax</div>
<div class="flexItem">bbbx</div>
<div class="flexItem">c c c c c cx</div>
</div>
</div>
来源:https://stackoverflow.com/questions/31844421/flexbox-how-to-add-margin-vertical-spacing-for-the-case-there-is-more-than-on