Fit Photos Into Their Boxes

In the last lesson, max-width: 100% and height: auto kept the seed swap photo inside its card, in its own 4:3 shape: four units wide for every three tall. Rosa has something else in mind. Volunteers send in photos of every shape, and she’d like each event card to show its photo as the same wide 16:9 strip, which also takes up less of a phone’s screen.

In this lesson, you’ll give the photo’s box a shape of its own, whatever shape the photo is, and then decide how the photo fills that box. You’ve already met the two choices that matter as background sizes. Start with the box.

Give the Box a Shape

An <img> element is a box like any other, with the photo drawn inside it. So far, the box has taken its shape from the photo. The width and height attributes made it 800 by 600, and since the last lesson, it has kept the photo’s own shape as it shrinks. To make every card’s photo the same shape, you set the box’s proportions instead.

The aspect-ratio property gives a box a shape by setting its width-to-height ratio, written with a slash. Add a rule for the photos in event cards at the end of events/events.css:

Language: CSS Filename: events/events.css
.event-card img {
  aspect-ratio: 16 / 9;
}

Save and scroll down to the seed swap card:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.