patterncsstailwindTip
aspect-ratio utility for responsive media embeds
Viewed 0 times
aspect-ratioaspect-video16:9responsive embediframevideo container
Problem
Embedded iframes (YouTube, Vimeo) or images need to maintain a 16:9 or 4:3 aspect ratio as they scale, but the classic padding-top hack is confusing and Tailwind's aspect-ratio utility behavior is not obvious.
Solution
Use
aspect-{ratio} utilities:<!-- 16:9 video embed -->
<div class="aspect-video">
<iframe class="w-full h-full" src="https://www.youtube.com/embed/..."></iframe>
</div>
<!-- Square image -->
<img class="aspect-square w-full object-cover" src="photo.jpg" alt="Profile" />
<!-- Custom ratio -->
<div class="aspect-[4/3] overflow-hidden">
<img class="w-full h-full object-cover" src="landscape.jpg" alt="" />
</div>
<!-- Responsive: square on mobile, video on desktop -->
<div class="aspect-square md:aspect-video">
<video class="w-full h-full object-cover" autoplay muted loop></video>
</div>Why
CSS aspect-ratio is natively supported in all modern browsers and replaces the old padding-top percentage hack. Tailwind's aspect-video is shorthand for aspect-[16/9].
Gotchas
- The element with aspect-ratio needs a defined width or the ratio has nothing to scale from.
- aspect-ratio does not clip overflow — add overflow-hidden if the child might exceed the container.
- For img elements, combine with object-cover and object-position to control cropping.
- Browser support: IE11 does not support CSS aspect-ratio. Use the padding-top polyfill approach if legacy support is needed.
Context
When embedding videos, displaying images in a grid, or building responsive media containers.
Revisions (0)
No revisions yet.