CSS
Adaptive Grid Card Layouts with Consistent Aspect Ratio
Implement a responsive grid for card-like elements that maintain a uniform aspect ratio and automatically adjust column counts based on viewport width, enhancing visual consistency.
.card-container {
display: grid;
/* auto-fill creates as many columns as fit, auto-fit would only create columns for existing items */
/* minmax ensures columns are at least 250px wide but never larger than 1fr */
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px; /* Space between grid items */
padding: 20px;
background-color: #f0f0f0;
}
.card {
background-color: #fff;
border: 1px solid #ddd;
border-radius: 8px;
overflow: hidden;
display: flex; /* Use flexbox inside card for content alignment */
flex-direction: column;
}
.card-content {
padding: 15px;
flex-grow: 1; /* Allow content to grow and push image up if needed */
}
.card-media {
width: 100%;
/* Maintain a 16:9 aspect ratio for the media area */
aspect-ratio: 16 / 9;
background-color: #e0e0e0; /* Placeholder color */
display: flex;
justify-content: center;
align-items: center;
font-size: 0.9em;
color: #666;
}
.card-media img {
width: 100%;
height: 100%;
object-fit: cover; /* Ensures image covers the area without distortion */
}
.card h3 {
margin-top: 0;
margin-bottom: 10px;
font-size: 1.2em;
}
.card p {
font-size: 0.9em;
color: #555;
line-height: 1.5;
}
How it works: This snippet creates an adaptive grid of cards. The `.card-container` uses `display: grid` with `grid-template-columns: repeat(auto-fill, minmax(250px, 1fr))` to dynamically adjust the number of columns based on available space, ensuring each card is at least 250px wide. Each `.card` utilizes `aspect-ratio: 16 / 9` on its media area (`.card-media`) to maintain a consistent visual shape regardless of content, crucial for a clean and predictable layout.