2

Using CSS Grid, how can I keep all of the children in one row when you don't know how many children there will be?

I need all children to have equal width, so if there are 2 children they will each have 50% width and if there are 3 children they each get 33.33% width etc.

.container {
   display: grid;
}

<div class='container'>
   <div>Child 1</div>
   <div>Child 2</div>
   <div>Child 3</div>
   // There maybe 4 or 5 children we don't know
</div>
maxshuty
  • 9,708
  • 13
  • 64
  • 77
Bill
  • 4,614
  • 13
  • 77
  • 132
  • Its probably better to use flexbox for variable amounts of children. –  Feb 26 '21 at 11:42

2 Answers2

5

Use a column flow and keep all the size 1fr

.grid {
  display: grid;
  grid-auto-columns: 1fr;
  grid-auto-flow:column;
}

.grid > div {
  background-color: tomato;
  height: 50px;
  border: 1px solid black;
}
Example 1:

<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Example 2:

<div class="grid">
  <div></div>
  <div></div>
</div>

Example 3:

<div class="grid">
  <div></div>
  <div></div>  
  <div></div>
  <div></div>  
  <div></div>
  <div></div>  
  <div></div>
  <div></div>  
  <div></div>
  <div></div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
0

This can be done easily CSS grid by using repeat, auto-fit, and minmax.

Essentially what we are doing here is setting the child elements to take up the full width of whatever their "grid container" is, and then we are setting the grid to be auto-fit and saying that each child will be a minimum of 50px or a maximum of 1fr.

Another good approach would be to just use grid-auto-columns and grid-auto-flow. Kind of depends on your specific use case for which is the better approach, but be sure to checkout Temani Afif's answer for the other solution.

.grid {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(50px, 1fr));
}

.grid > div {
  background-color: tomato;
  height: 50px;
  width: 100%;
  border: 1px solid black;
}
Example 1:

<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Example 2:

<div class="grid">
  <div></div>
  <div></div>
</div>

Example 3:

<div class="grid">
  <div></div>
  <div></div>  
  <div></div>
  <div></div>  
  <div></div>
  <div></div>  
  <div></div>
  <div></div>  
  <div></div>
  <div></div>
</div>
maxshuty
  • 9,708
  • 13
  • 64
  • 77