Create a responsive grid of items using CSS-Grid layout, that flows and wraps without media queries.
Using CSS-Grid layout, and its auto-fit
and minmax
properties, you can eliminate the need for media query resizing.
auto-fit
fits the currently available columns into the container space by expanding them.
minmax
allows for setting a minimum or maximum size for the cells, but can also take auto
as a value, allowing for the cell to grow to accommodate the content.
<div class="grid"> <div class="item">Item</div> <div class="item">Item</div> <div class="item">Item</div> </div> <br> <div class="grid-100"> <div class="item">100px</div> <div class="item">100px</div> <div class="item">100px</div> </div>
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); grid-gap: 16px; } .item { justify-content: center; align-items: center; background: silver; color: black; } .grid-100 { display: grid; grid-template-columns: repeat(3, 100px); grid-gap: 16px; }
To create a responsive grid, we use this rule:
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
grid-gap: 16px;
This gives us a grid of (at least) 100px
-wide columns, and the layout will display as many of those as it can in a row. Any that don’t fit will be moved to a new row. If there is enough room to fit multiple columns, they will expand to fit the space (thus the 1fr
value in minmax()
).
It’s saying “For each row, repeat as many 100px
-wide columns as you can fit in the container, and expand those that can fit so that they take up the entire row, with 16px
in between each row and column.”
This is being used currently on the Movies page.