Images

Now let's look at Oscar's picture. It has no class yet, and still it fits into the card nicely. That's Preflight again. It gives all images these styles:

img {
	display: block;
	max-width: 100%;
	height: auto;
}
  • display: block: the picture is a block, on its own line. Without it, a browser shows an image inline, like a word in a sentence, and leaves a small gap below it.
  • max-width: 100%: the picture is never wider than its parent. Our picture is 600 pixels wide, but it shrinks to the width of the card.
  • height: auto: the height follows the width, so the picture keeps its aspect ratio (its shape: how many times wider than tall it is) and doesn't get distorted.

Cards on a website, though, usually have pictures of the same height, whatever the shape of the photos. When you set both the width and the height of a picture, its box gets a different shape from the picture's own, and the CSS property object-fit decides how the picture fills it:

ClassCSSWhat it does
object-fillobject-fit: fill;Stretches or squeezes the picture to the size of the box. This is the default.
object-coverobject-fit: cover;Fills the whole box and keeps the aspect ratio. What sticks out gets cut off, as with a photo set as a phone's wallpaper.
object-containobject-fit: contain;The whole picture fits into the box and keeps the aspect ratio; the rest of the box stays empty.

Here is Oscar's picture in a box that is twice as wide as it is tall (the dashed line):

Oscar squeezed to the shape of the boxobject-fill
Oscar filling the box, cut off at the top and bottomobject-cover
Oscar whole in the box, with empty space on the sidesobject-contain

Most of the time, you want object-cover: the box is filled, and the cat doesn't look squashed. Let's try it step by step.

Instructions

Add the class h-48 (height: 12rem, 192 pixels) to Oscar's picture. It doesn't have a class attribute yet, so write class="h-48" into the img tag. The picture gets lower, but also narrower: the browser keeps its aspect ratio, so a smaller height comes with a smaller width.

Add the class w-full (width: 100%). The picture fills the card's width again, but now it's squashed: when both its width and height are set, the default object-fill stretches it to the size of its box.

Add the class object-cover. The picture has its own aspect ratio again and fills the whole box: the browser cuts off a strip at its top and bottom.

Start programming for free

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

Or sign up with:

5/10