Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Control Image Aspect Ratio Using CSS

    Damon BauerDamon Bauer

    Resize images and videos to fill their parent and maintain their aspect ratio with pure CSS. The new object-fit and object-position properties allow you to scale images and videos, much like you could with background-size and background-position.

    cssCSS
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 I'll start by selecting the image. I'll set its width to 90 viewport width units. I'll set its height to 75 viewport height units. I'll also add a border, so that we can see its boundaries clearly.

    00:18 Let's set object fit to its default value of fill. Fill is going to stretch the image, regardless of its aspect ratio, to fill the container. Next, I'll change object fit to a value of contain. This will increase or decrease the image size to fill the box, but it won't change the aspect ratio.

    00:41 You'll see the empty space here at the top and the bottom of the container, confirming that the aspect ratio of the image itself hasn't changed. I'll change object fit to a value of cover. This might be the most useful value for object fit. It tells the image to fill the height and width of its container, and to maintain its aspect ratio.

    01:02 If necessary, the image will be cropped to fit to the container size, which you can see. When I resize my browser down, you'll see the sides of the image being cut off, but the main part of the image keeps its aspect ratio.

    01:16 You can also set object fit to none, which just tells the image to keep its original size. The last value we can set to object fit is scale-down, which will use either none or contain, whichever one outputs the smallest dimensions of the image. Let's set the object fit value back to cover. We'll look at object position.

    01:43 This property works in the same way as background position, allowing you to move the image around inside of its container. By default, object position has a value of 50 percent or the exact center of the container. Let's change this to something like 20 pixels and 10 pixels. This says, "Set the top left of the image to 20 pixels from the left edge of the container and 10 pixels from the top edge."

    Discuss

    Discuss