Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple flexboxes with margin-right, except the last one in the row? Without JS?

Tags:

html

css

flexbox

See the following image:

enter image description here

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.

My question:

Is there any way to get the top-right example, as well as the nice-to-haves, with flex-boxes, but without resorting to JS, display:table, or negative margin shenanigans?

like image 924
Slater Avatar asked Feb 10 '23 01:02

Slater


1 Answers

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>
like image 71
Oriol Avatar answered Feb 12 '23 15:02

Oriol