Aspect Ratio in TailwindCSS
? Aspect Ratio Utilities in Tailwind CSS
Tailwind CSS includes utilities to control the aspect ratio of elements, ensuring they maintain a specific width-to-height ratio regardless of the size.
How to Use Aspect Ratio
Tailwind provides the aspect-[ratio] utilities, such as:
| Class | Ratio | Description |
|---|---|---|
aspect-auto | auto | Default aspect ratio behavior |
aspect-square | 1 / 1 (1:1) | Makes element perfectly square |
aspect-video | 16 / 9 (16:9) | Standard video aspect ratio |
aspect-[number] | Custom ratio, e.g., aspect-[3/2] | Any custom ratio with square brackets |
How it works:
Behind the scenes, Tailwind sets the element’s height relative to its width using padding-top trick:
.aspect-video { position: relative; padding-top: 56.25%; /* 9/16 = 0.5625 */ height: 0;}.aspect-video > * { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%;}Tailwind does this automatically when you apply the utility class.
Example:
<div class="aspect-w-16 aspect-h-9"> <iframe src="https://www.youtube.com/embed/xyz" class="w-full h-full"></iframe></div>Note: Above uses older Tailwind syntax (aspect-w-*, aspect-h-*) which requires the aspect-ratio plugin.
Tailwind v3+ Built-in Aspect Ratio Classes
Since Tailwind 3.0+, aspect ratio is built-in:
<div class="aspect-square bg-gray-300">Square Box</div><div class="aspect-video bg-gray-300 mt-4">16:9 Video Box</div><div class="aspect-[3/2] bg-gray-300 mt-4">Custom 3:2 Aspect Ratio</div>Use Cases
Responsive videos or iframes
Image containers that maintain ratio
Cards or divs that need fixed ratio regardless of width
If you want, I can help you with how to install/use the aspect ratio plugin for older Tailwind versions or create custom ratios!