CSS
Create a Responsive, Auto-Fitting Grid Layout
Learn how to build highly flexible and responsive grid layouts that automatically adjust item count and size based on screen width using CSS Grid's auto-fit and minmax functions.
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.grid-item {
background-color: #f0f0f0;
padding: 15px;
border-radius: 8px;
text-align: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
How it works: This snippet creates a responsive grid layout. The `display: grid;` property initializes the grid container. `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));` is the core of its responsiveness: `auto-fit` automatically creates as many columns as can fit, while `minmax(250px, 1fr)` ensures each column is at least 250px wide but can grow to take up an equal share of the remaining space (1fr). `gap` adds space between grid items. This setup is ideal for galleries or product listings that need to adapt to various screen sizes.