CSS
CSS Grid: Responsive Auto-Fitting Card Layout
Create a highly responsive grid of cards or items that automatically adjusts column count based on screen size, using CSS Grid's `auto-fit` and `minmax` functions.
.grid-container {
display: grid;
/* Auto-fits columns, each at least 250px wide, growing to fill space */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px; /* Spacing between grid items */
padding: 20px;
background-color: #f9f9f9;
font-family: sans-serif;
}
.grid-item {
background-color: #fff;
border: 1px solid #ddd;
padding: 15px;
text-align: center;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
border-radius: 5px;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
.grid-item h3 {
margin-top: 0;
color: #333;
}
.grid-item p {
color: #666;
font-size: 0.9em;
}
How it works: This snippet creates a dynamic, responsive grid layout for cards or similar elements. By using `display: grid` and `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))`, the grid will automatically create as many columns as can fit, with each column being at least 250px wide but also growing to fill available space evenly. The `gap` property provides consistent spacing between grid items, making it ideal for product listings or galleries.