Is it possible to recreate this using display: grid
and gap
instead of display: flex
and margin
, without the CSS knowing how many items there are?
.item {
width: 50px;
height: 50px;
flex-basis: 50px;
flex-grow: 0;
flex-shrink: 0;
background: orange;
margin-right: 10px;
}
.item:last-child {
margin-right: 0;
}
#items {
display: flex;
flex-direction: row;
padding: 10px;
margin: 10px;
border: 2px solid red;
width: fit-content;
}
<div id="items">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
Is there a way to tell a display: grid
element that you want extra items to appear in new columns instead of new rows?
Use grid-auto-flow: column;
on the id
#items
with your grid display. This is equivalent to flex-direction: row;
when using flex
.
.item {
width: 50px;
height: 50px;
flex-basis: 50px;
flex-grow: 0;
flex-shrink: 0;
background: orange;
margin-right: 10px;
}
.item:last-child {
margin-right: 0;
}
#items {
display: grid;
grid-auto-flow: column;
padding: 10px;
margin: 10px;
border: 2px solid red;
width: fit-content;
}
<div id="items">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>