By Vivian
/November 5, 2021
You probably heard these 2 words a lot when working with images or videos but probably don’t know the definition, if that’s the case then I’ll fix that for you right now:
“The aspect ratio of an image is the ratio of its width to its height. It is commonly expressed as two numbers separated by a colon, as in 16:9.”
Thanks, Wikipedia!
Now, why is this important?
When you work with images, you have the ability to change its width and height with CSS and even with its native attributes (width="" height="") but making those images responsive for all screen sizes would take a lot of CSS or classes, in the case Tailwind CSS.
You can fix that problem by using aspect ratio. Why? Because when you use aspect ratio, you essentially make the image have the same proportions no matter the screen size, the image will automatically scale based on available space.
Ok, now you know what aspect ratio is, so let’s talk about the most common ones:
Let’s see how we can use aspect ratio in our code.
Luckily for us, the Tailwind Labs team created a plugin specifically for using aspect ratios. You can install by:
npm install @tailwindcss/aspect-ratio
plugins: [
require('@tailwindcss/aspect-ratio'),
],
The plugin comes with some default values so we can use it out of the box.
Now, let’s say we want to add a video embed to our site and we want it to be 16:9, here’s the code for that:
<div class="aspect-w-16 aspect-h-9">
<iframe ...>
</div>
Now, you may ask, why did I put the aspect ratio code on the parent element instead of the element I want to target? That’s because of how the plugin works.
You see, until recently, we didn’t have a native way of using aspect ratio in CSS so we had to use a hack that involved padding in % values and position absolute. Pretty weird hack I know, but the good thing about its that it works on all browsers. If you want to dig deep into it you can see the plugin’s CSS output here.
Let me give you more examples.
Here’s the code for a square image:
<div class="aspect-w-1 aspect-h-1">
<img ...>
</div>
And here’s one for the older TV’s:
<div class="aspect-w-4 aspect-h-3">
<img ...>
</div>
Pretty straightforward, you basically take the first digit and add it to aspect-w and your second digit and add it to aspect-h.
Now know how to use the plugin but what if we want to customize it, the plugin only has values from 1 to 16 and if we want to use, lets say, an ultrawide aspect ratio, we would need to add it the tailwind config, it would be something like this:
module.exports = {
theme: {
extend: {
aspectRatio: {
21: '21',
32: '32'
}
}
}
}
Now you can do:
<div class="aspect-w-32 aspect-h-9">
<img ...>
</div>
That’s it for this post, now you know what aspect ratio is, what are the most common ones, how you can use it in your code with the Aspect Ratio plugin, and how you can add values to the plugin.
Stay tuned for more articles like this coming soon!