CSS Advanced: Variables, Motion and Modern CSS
Modern CSS: calc, clamp and Friends
In this lesson you will
- Do arithmetic in CSS with calc
- Use clamp for fluid, bounded sizes
- Keep media in proportion with aspect-ratio and object-fit
Introduction
Early CSS values were fixed. Modern CSS can calculate and adapt. With a few functions you can write sizes that grow and shrink with the screen, with no media query at all.
calc(): do the maths
calc() lets you mix units, such as a percentage and a fixed size.
Put spaces around + and - inside calc(). calc(100%-40px) is invalid.
Quick quiz
What does width: calc(100% - 40px) do?
min(), max() and clamp()
min(a, b)picks the smaller value. Good for a width that should not exceed a limit.max(a, b)picks the larger value.clamp(minimum, preferred, maximum)keeps a value between two limits while it follows a preferred, flexible value.
vw is 1 percent of the viewport width. Try resizing: the clamp heading smoothly changes size and stops at its limits. This is called fluid typography.
Keep shape with aspect-ratio
aspect-ratio makes a box keep a width-to-height shape as it resizes.
object-fit for images
When an image is forced into a box that is a different shape, object-fit: cover crops it to fill the box without stretching, similar to a profile photo.
HTML
img {
width: 200px;
height: 200px;
object-fit: cover;
}Quick quiz
What does clamp(1rem, 4vw, 2rem) guarantee?
Try it yourself
Make the card width min(100%, 360px), and give the card a 4 / 3 aspect ratio.
Summary
calc()mixes units and does arithmetic.min(),max()andclamp()make sizes flexible but bounded.aspect-ratiokeeps a shape, andobject-fit: covercrops an image to fit.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading