Responsive Images in CSS Grid and Flexbox Layouts
Generate correct sizes attributes for images inside CSS Grid and Flexbox containers where image widths change dynamically with the layout.
Detailed Explanation
Responsive Images in Grid and Flex Layouts
When images live inside CSS Grid or Flexbox containers, calculating the correct sizes attribute requires understanding how your layout responds to different viewport widths.
CSS Grid Example
For a responsive grid that switches from 1 to 2 to 3 columns:
.grid {
display: grid;
gap: 1rem;
grid-template-columns: 1fr;
padding: 1rem;
}
@media (min-width: 640px) {
.grid { grid-template-columns: repeat(2, 1fr); }
}
@media (min-width: 1024px) {
.grid { grid-template-columns: repeat(3, 1fr); }
}
The matching sizes attribute:
<img
srcset="card-320w.webp 320w,
card-480w.webp 480w,
card-640w.webp 640w,
card-768w.webp 768w"
sizes="(max-width: 640px) calc(100vw - 2rem),
(max-width: 1024px) calc(50vw - 1.5rem),
calc(33.33vw - 1.33rem)"
alt="Card image"
loading="lazy"
/>
Calculating sizes for Grid with Gaps
The formula accounts for padding and gap:
- 1 column:
calc(100vw - 2 * padding) - 2 columns:
calc((100vw - 2 * padding - gap) / 2)≈calc(50vw - 1.5rem) - 3 columns:
calc((100vw - 2 * padding - 2 * gap) / 3)≈calc(33.33vw - 1.33rem)
Flexbox Wrapping Layout
.flex-grid {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.flex-grid img {
flex: 1 1 300px;
max-width: 100%;
}
For flex items with a 300px basis, the sizes attribute should reflect the actual rendered width:
sizes="(max-width: 640px) calc(100vw - 2rem),
(max-width: 960px) calc(50vw - 1.5rem),
calc(33.33vw - 1.33rem)"
Masonry and Auto-Fill Grids
For grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)), the number of columns varies dynamically. Approximate with breakpoint ranges that match when columns are added.
Use Case
Image galleries, blog post grids, portfolio layouts, and any multi-column layout where images resize based on the container. Getting sizes right in grid layouts prevents oversized image downloads that waste bandwidth.
Try It — Responsive Image Srcset Generator
Related Topics
The sizes Attribute — Telling the Browser How Big Your Image Will Be
Fundamentals
The srcset Attribute Explained — Width Descriptors and Resolution Switching
Fundamentals
Responsive Product Images for E-Commerce Sites
Use Cases
Responsive Background Images — CSS image-set() and Media Queries
Use Cases
Common srcset and sizes Mistakes — How to Avoid Them
Best Practices