Calc() in sizes Attribute
What you'll learn: How to use CSS's calc() function inside the sizes attribute to create mathematically precise responsive image sizing rules.
Why Combine calc() with sizes?
In the previous lesson, you learned that sizes can use viewport units like 100vw or fixed values like 400px. But what if your image's actual display width is almost full viewport, but needs to account for padding or gutters? Or what if it's viewport-based minus a fixed sidebar width?
That's where calc() shines—it lets you combine different units with mathematical operations right inside the sizes attribute.
How It Works
The calc() function performs calculations mixing viewport units, percentages, and fixed units. Think of it like a calculator that speaks both "viewport language" and "pixel language" fluently.
Syntax pattern:
<img
srcset="image-400.jpg 400w,
image-800.jpg 800w,
image-1200.jpg 1200w"
sizes="(min-width: 1000px) calc(100vw - 300px),
calc(100vw - 40px)"
src="image-400.jpg"
alt="Responsive image">
Here's what this says:
- On large screens (≥1000px): Image width = full viewport minus 300px sidebar
- On smaller screens: Image width = full viewport minus 40px total padding (20px each side)
Common Patterns
calc(100vw - 2rem)— full width minus fixed paddingcalc(50vw - 100px)— half viewport minus a gapcalc((100vw - 80px) / 2)— split viewport accounting for gutters
Key Takeaway: Use calc() in sizes to precisely describe image widths that combine viewport-relative and fixed measurements, helping browsers select the perfect image source for complex layouts.