Ask any question about CSS here... and get an instant response.
Post this Question & Answer:
How can I create a responsive CSS grid layout that adjusts columns based on screen size?
Asked on May 02, 2026
Answer
To create a responsive CSS grid layout that adjusts columns based on screen size, you can use CSS Grid's `repeat()` function with the `auto-fit` or `auto-fill` keywords and media queries for finer control. This allows the grid to automatically adjust the number of columns based on the available space.
<!-- BEGIN COPY / PASTE -->
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 10px;
}
.grid-item {
background-color: #ccc;
padding: 20px;
text-align: center;
}
</style>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- The `grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));` rule allows the grid to create as many columns as fit into the container, each with a minimum width of 150px and a flexible maximum width.
- Using `auto-fit` makes the grid items stretch to fill the container space, while `auto-fill` would create empty tracks if there's extra space.
- Media queries can be added for more specific adjustments at different breakpoints, if needed.
- The `gap` property sets the spacing between grid items.
Recommended Links:
