CSS aspect-ratio & object-fit Generator
Tired of distorted squished images or annoying Cumulative Layout Shifts (CLS) while assets load? The modern aspect-ratio and object-fit: cover duo solves responsive media layout once and for all.
/* Müasir responsiv media bloku */
.media-card {
width: 100%;
max-width: 480px;
aspect-ratio: 16 / 9; /* Sıfır CLS sıçrayışı */
overflow: hidden;
border-radius: 12px;
}
.media-card img {
width: 100%;
height: 100%;
object-fit: cover; /* Təhrif olmadan kəsilir */
object-position: 50% 50%; /* Fokus mərkəzi */
}
How to use it
- Select a preset aspect ratio (16:9 video, 1:1 avatar, 4:3 classic photo, 9:16 vertical Shorts, or 21:9 ultrawide).
- Toggle the
object-fitmode (cover, contain, fill, none) and compare clean cropping against distorted stretching. - Click anywhere on the preview image to pin the
object-positionfocal point crosshair. - Resize the container with the width slider, review CLS diagnostic metrics, and copy production-ready CSS.
How it works
What does aspect-ratio do?
The aspect-ratio property establishes a preferred aspect ratio for the box (width / height), such as 16 / 9 or 1 / 1. It supersedes archaic padding-top: 56.25% percentage hacks, enabling the browser to immediately reserve the exact layout box before network media arrives.
Eliminating Cumulative Layout Shift (CLS)
Cumulative Layout Shift (CLS) is a vital Google Core Web Vital metric. Without explicit proportions, an image pushes downstream text down abruptly when it downloads. Setting aspect-ratio completely prevents layout shifts.
/* Zero CLS layout jump guaranteed */
.hero-media {
width: 100%;
aspect-ratio: 16 / 9;
}
The object-fit and object-position synergy
object-fit: cover scales images and videos to fill their container box while preserving natural proportions, trimming excess edges. object-position dictates the focal alignment anchor (e.g. keeping a face or logo centered during responsive cropping).
.avatar-img {
width: 100%;
height: 100%;
object-fit: cover;
object-position: 50% 20%; /* Keeps the face in frame */
}
FAQ
What is the difference between object-fit: fill and cover?
fill violently distorts and squishes the media to match container dimensions. cover preserves the natural aspect ratio, smoothly clipping excess margins without distortion.
Is aspect-ratio widely supported?
Yes! All modern browsers (Chrome, Edge, Safari 15+, Firefox) provide complete cross-platform support with over 96% global coverage.
Does this work on embedded YouTube iframes?
Yes, iframe { width: 100%; aspect-ratio: 16 / 9; height: auto; } is the modern industry best practice for embedded responsive players.