CSS/HTML
Responsive CSS Grid Card Layout with minmax()
Create a dynamic and responsive grid-based card layout that automatically adjusts the number of columns based on screen size using `grid-template-columns` and `minmax()`.
<div class="card-grid">
<div class="card"><h3>Card 1</h3><p>Content for card 1.</p></div>
<div class="card"><h3>Card 2</h3><p>Content for card 2.</p></div>
<div class="card"><h3>Card 3</h3><p>Content for card 3.</p></div>
<div class="card"><h3>Card 4</h3><p>Content for card 4.</p></div>
<div class="card"><h3>Card 5</h3><p>Content for card 5.</p></div>
<div class="card"><h3>Card 6</h3><p>Content for card 6.</p></div>
</div>
<style>
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; }
.card-grid {
display: grid;
/* Automatically adjust columns: at least 250px, but fill available space */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px; /* Space between grid items */
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.card {
background-color: #fff;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
display: flex; /* Flex inside card for content alignment */
flex-direction: column;
justify-content: space-between;
}
.card h3 {
margin-top: 0;
color: #333;
}
.card p {
color: #666;
}
</style>
How it works: This snippet creates a flexible card layout using CSS Grid. `display: grid` makes the container a grid. The key to responsiveness is `grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))`. `auto-fit` creates as many columns as can fit into the available space, while `minmax(250px, 1fr)` ensures each column is at least 250px wide but also grows to fill available space equally (`1fr`). `gap` adds consistent spacing between the cards.