I have a container that is 608px
wide, and my design calls for having 3 items per row. Where each item is 192px
. And only the first 2 items in the row have a margin-right
of 16px
.
The problem is the CSS is adding a margin-right
of 16px
to all items.
How can I update the code to make it 3 items per row, where just the 1st and 2nd items per row have the margin-right
padding?
I had a hacky version working where I made the margin-right
and margin-left
8px
and then added a negative -8px
margin on the container but that feels hacky and I'm curious if there is now a more elegant way to accomplish this with CSS3.
.container {
width: 608px;
min-width: 608px;
max-width: 608px;
background: #efefef;
display: flex;
flex-wrap: wrap;
}
.item {
width: 192px;
min-width: 192px;
max-width: 192px;
margin: 0 16px 16px 0;
border: 1px solid #ccc;
box-sizing: border-box;
}
<div class="container">
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
</div>
You can add pseudo selector nth-child(3n+3)
to remove the right margin for every .item
that is multiple of 3 (ie. 3,6,9...). Try adding this piece of code to yours.
.item:nth-child(3n+3) {
margin-right: 0;
}
Here is the CSS-grid solution where you can easily control the gap between element and you also don't need to explicitly specify a width for them:
.container {
width: 608px;
display:grid;
grid-template-columns:repeat(3, 1fr);
grid-column-gap:16px;
background: #efefef;
}
.item {
border: 1px solid #ccc;
box-sizing: border-box;
}
<div class="container">
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With