Is it possible to place all the items in grid in one row when I don't know the number of columns?
I’m trying to make a grid container that has undefined number of columns and I want it to be one row. Is there any way to do this in CSS?
.grid { display: grid; grid-gap: 5px; } .grid > div { background: #ccc; min-height: 100px; }
<div class="grid"> <div></div> <div></div> <div></div> </div>
There is two ways actually.
- Using
grid-template-columns: repeat(auto-fit, minmax(1px, 1fr));
. Fits new columns automatically and determines it’s mimimum and maximum width. More about Grid Template Columns and auto-fit/auto-fill. - Using
grid-auto-flow: column;
. Determines automatically placement behavior of grid cells. More about Grid auto flow.
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(1px, 1fr)); grid-gap: 5px; margin-bottom: 5px; } .grid2 { display: grid; grid-auto-flow: column; grid-gap: 5px; margin-bottom: 5px; } .grid > div, .grid2 > div { background: #ccc; min-height: 100px; }
<div class="grid"> <div></div> <div></div> <div></div> </div> <div class="grid2"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div>