Handling images improperly is the #1 cause of broken web layouts and poor Google Core Web Vitals (Cumulative Layout Shift - CLS). Modern CSS provides powerful properties like object-fit and aspect-ratio to render pictures gracefully without distortion.
When an <img> has fixed dimensions, setting width and height can stretch or squish the photo. object-fit controls how the image scales to fit its content box:
| Value | Visual Behavior | Aspect Ratio Preserved? |
|---|---|---|
fill |
Default. Stretches or squeezes image to fit box. | No (Image looks distorted and ugly!) |
cover |
Fills entire container, cropping excess edges. | Yes (Gold standard for cards and avatars) |
contain |
Scales image to fit completely inside container. | Yes (Leaves letterbox letterbox bars) |
scale-down |
Takes smaller of none or contain. |
Yes |
Before aspect-ratio was introduced, developers had to use the infamous "padding-bottom hack" to reserve space for responsive video containers. Today, you define aspect ratios in a single line:
/* Perfect 16:9 widescreen video embed container */
.video-responsive {
width: 100%;
aspect-ratio: 16 / 9;
background-color: #0f172a;
}
/* Perfect 1:1 square Instagram-style avatar */
.avatar-square {
width: 120px;
aspect-ratio: 1 / 1;
object-fit: cover;
border-radius: 8px;
}
Always specify HTML width and height attributes on images in addition to CSS aspect-ratio. This enables the browser to reserve the exact pixel space before image bytes download, preventing sudden, jarring page jumps!
Boost your CSS and front-end development proficiency by exploring these closely connected topics:
Understand margins, borders, padding, content and the universal box-sizing fix.
Master 1D alignment, justify-content, align-items, flex-wrap and responsive flow.
Build powerful two-dimensional grid layouts with template areas and fr units.
Eliminate styling conflicts and master selector weights from 0,0,0,1 to !important.