CSS
Dynamic Responsive Card Grid with CSS Grid auto-fit
Create a flexible, responsive grid layout for cards or items that automatically adjusts column count based on viewport size using CSS Grid's `auto-fit` and `minmax` functions without media queries.
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px;
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.card {
background-color: #f0f0f0;
border: 1px solid #ddd;
padding: 15px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
How it works: This CSS snippet creates a highly responsive grid of cards that adapts dynamically to the viewport size. By using `display: grid;` on the container and `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));`, the grid automatically calculates how many columns can fit. `auto-fit` fills the available space with as many columns as possible, while `minmax(280px, 1fr)` ensures each column is at least 280 pixels wide but can grow to fill 1 fraction of the available space, maintaining equal column widths. `gap` provides spacing between grid items.