object-fit & aspect-ratio
Master responsive media by controlling image scaling without distortion and locking container proportions.
What they are
aspect-ratio allows you to lock an element's proportions. If you set aspect-ratio: 16 / 9, the browser will automatically calculate the height based on the width to maintain that exact rectangle.
object-fit dictates how the content of a replaced element (like an <img> or <video>) should resize to fit its container.
Why it matters
When building responsive grids (like a gallery of product photos), you usually want all image boxes to be exactly the same size. But user-uploaded photos come in all shapes and sizes.
If you force an image to be width: 100% and height: 100%, it will squish and stretch to fit the box, looking terrible.
object-fit: cover solves this by telling the image to fill the box entirely while maintaining its intrinsic proportions, cropping any overflow.
How to use them
1. **Lock the box**: Apply aspect-ratio: 1 / 1 (a perfect square) to the image container.
2. **Fill the box**: Make the image fill the container using width: 100%; height: 100%.
3. **Fix the distortion**: Apply object-fit: cover to the image to crop it perfectly, or object-fit: contain to letterbox it.
Try it
Toggle the different object-fit values to see how the browser resolves the conflict between the image's original dimensions and its fixed container size.
Image Scaling
object-fit
How should the wide 2:1 image fit into the 1:1 square box?
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
aspect-ratio: w / hlocks an element's proportions, reserving space before images load to prevent layout shifts.- Forcing an image's
widthandheightcauses terrible distortion. object-fit: coverfixes distortion by filling the box and cropping the overflow.object-fit: containfixes distortion by shrinking the image to fit entirely, leaving empty letterbox space.
Done with this concept?
Mark it complete to track your progress. No login needed.