Multiple Flexboxes With Margin-right, Except The Last One In The Row? Without JS?
See the following image: Current setup is at top-left. If I add more red boxes, they will wrap to the next line, leaving a 10px right margin of the last red box on the first line.
Solution 1:
Since in the image you use width: 25%
, I assume you want 4 element per line.
Therefore, you only need
.red-box {
width: calc(25% - 30px/4);
margin: 0 10px 10px 0;
}
.red-box:nth-child(4n) {
margin-right: 0;
}
#wrapper {
display: flex;
flex-wrap: wrap;
background: #01FF00;
}
.red-box {
width: calc(25% - 30px/4);
margin: 0 10px 10px 0;
height: 100px;
background: red;
}
.red-box:nth-child(4n) {
margin-right: 0;
}
<div id="wrapper">
<div class="red-box"></div>
<div class="red-box"></div>
<div class="red-box"></div>
<div class="red-box"></div>
<div class="red-box"></div>
<div class="red-box"></div>
<div class="red-box"></div>
</div>
Solution 2:
Yes, just use .red-box:not(:last-child)
as your CSS selector, instead of .red-box
only.
To make it work for multiple rows, all you have to do is wrap each row within a div. See this fiddle.
Solution 3:
I know I'm almost 6 years late here, but for anyone having a similar issue, the solution for both cases, is to wrap the flex container with another div, apply negative margins to flex container, and finally, give back the same amount of margin to each flex item as such:
.wrapper {
border: 4px dotted rgb(96, 139, 168);
width: 500px;
}
.box {
display: flex;
flex-wrap: wrap;
margin:-10px;
}
.box>* {
flex: 1 1 160px;
margin: 10px;
/*presentation styles*/
background-color:#4a56cada;
color:white;
height:40px;
}
<div class="wrapper">
<div class="box">
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
<div>Five</div>
<div>Six</div>
<div>Seven</div>
<div>Eight</div>
<div>Nine</div>
<div>Ten</div>
</div>
</div>
A more detailed explanation can be found in the MDN docs
Post a Comment for "Multiple Flexboxes With Margin-right, Except The Last One In The Row? Without JS?"