Home > Enterprise >  Simulate flex-direction:row using display:grid
Simulate flex-direction:row using display:grid

Time:04-08

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 ></div>
<div ></div>
<div ></div>
<div ></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?

CodePudding user response:

Use grid-auto-flow: column; on your grid.

.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 ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

Here is what you need

display: grid;
grid-template-columns: repeat(4, 1fr);
gap:10px;

i did not see how many items there are, Then temani afif got you

grid-auto-flow: column;
gap:10px;
``
  • Related