Let's use Aspect ratio with Tailwind - @tailwindcss/aspect-ratio

Let's use Aspect ratio with Tailwind - @tailwindcss/aspect-ratio

Aspect Ratio CSS / Tailwind / React / Gatsby

Hi, I need to create a widget with 3 different sizes, horizontal, vertical, square. So let's do this together. If you have any cool ideas, please share them in the comment section.

The @tailwindcss/aspect-ratio plugin adds aspect-w-{n} and aspect-h-{n} classes that can be combined to give an element a fixed aspect ratio.

<div class="aspect-w-16 aspect-h-9">
  <iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

checkout: tailwindcss.com/docs/plugins#aspect-ratio github.com/tailwindlabs/tailwindcss-aspect-..

So let's go. First, install:

yarn add @tailwindcss/aspect-ratio

or

npm install yarn add @tailwindcss/aspect-ratio

go to tailwind.config.js add

require("@tailwindcss/aspect-ratio")
// tailwind.config.js
module.exports = {
  // ...
  plugins: [
    require('@tailwindcss/typography'),
    require('@tailwindcss/forms'),
    require('@tailwindcss/line-clamp'),
    require('@tailwindcss/aspect-ratio'),
  ]
}

done. We can now play with the images. with:

aspect-w-{x}
aspect-h-{x}

Wrap your with a div, it's important to know aspect-ratio: width / height; using CSS this is using (the old padding-bottom trick ) you need to assign the aspect ratio to a parent element, and make the actual element you are trying to size the only child of that parent.

aspect ratio  | padding-bottom value
--------------|----------------------
    16:9      |       56.25%
    4:3       |       75%
    3:2       |       66.66%
    8:5       |       62.5%

Horizontal / Landscape

<div className="aspect-w-16 aspect-h-9">
<Horizontal />
</div>

to get 16/9 Horizontal done.

Square: For the square we need to make something like the following:

aspect-ratio: 1 / 1;
<div className="aspect-w-1 aspect-h-1">
<Sqaure />
</div>
  1. vertical/ Portrait
<div className="aspect-w-9 aspect-h-16">
<Horizontal />
</div>

It's a flex-wrap, see ya, @itaycode