Aspect Ratio

A fixed height works, but it doesn't take the width into account: in a wide card, a picture 192 pixels tall is a low strip, and in a narrow one, it's almost a square. Our card is never wider than 24rem (max-w-sm), but pictures elsewhere on a website, for example across the whole page, change their width a lot. So it's often better to give a picture a shape: an aspect ratio, the ratio of its width to its height. That's what the CSS property aspect-ratio does, and the browser then works out the height from the width:

aspect-ratio: 16 / 9; /* 16 parts wide, 9 parts tall */
ClassCSSShape
aspect-squareaspect-ratio: 1 / 1;a square
aspect-videoaspect-ratio: 16 / 9;a video or a TV screen
aspect-4/3aspect-ratio: 4 / 3;any ratio, written as a fraction
aspect-autoaspect-ratio: auto;the element's own ratio

For an aspect ratio to work, the element can't have both its width and its height set: one of them is given (here the width, w-full), and the ratio works out the other one. If you leave h-48 on the picture, the ratio is ignored.

Together with object-cover, you can give any photo the shape you want, and it won't get distorted. That's why you'll often see this trio of classes on pictures: w-full aspect-video object-cover.

Instructions

On Oscar's picture, replace the class h-48 with aspect-video. The picture now always has the shape of a video, 16 : 9. (Try aspect-square too, and then go back to aspect-video.)

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/10