This post was originally published at thedevspace.io. Everything you need to master web development, all in one place.

Previously, we talked about how to embed images using the element. Just like any other block-level element, you can define a size for the image using the width and height attributes.

src="images/image.png" alt="Image" width="500" height="500" />

Visit Code Demo ↗

In this case, we defined the element as a 500x500 box, but the actual image has a different aspect ratio, so it gets squished to fit inside. This might not be ideal because, in most cases, you want the image to keep its original aspect ratio.

Object fit

To solve this problem, you can use the object-fit property to specify how you wish the image to be displayed inside the defined box. The default option is fill, which means the images will be stretched or squished to fill the entire space, changing the image's aspect ratio.

To avoid that, you can set object-fit to contain. The image will shrink to fit inside the box.

Visit Code Demo ↗

Alternatively, you can set object-fit to cover, which works the other way. It will zoom in on the image until it fills the entire box.

Visit Code Demo ↗

Object position

Notice that it doesn't matter if you set object-fit to fill or cover. The browser will always zoom in on the center of that image. You can change how the image is positioned inside the box using the object-position property.

The property accepts keyword values such as top, bottom, left, and right, or combinations of these values such as top left, bottom right, and so on.

You can also micromanage the positioning of the image by specifying either percentage or length values.

object-position: <horizontal> <vertical>;

Visit Code Demo ↗

Read More

If you found this guide helpful, follow us on social media for more tips, tutorials, and updates on web development:

🔹 TheDevSpace | LinkedIn

🔹 TheDevSpace | X

🔹 TheDevSpace | Threads

Let's stay connected! 🚀