Previously, we talked about how to embed images using the <img>
element. Just like any other block-level element, you can define a size for the image using the width
and height
attributes.
1<img src="images/image.png" alt="Image" width="500" height="500" />
In this case, we defined the <img>
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.
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.
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.
1object-position: <horizontal> <vertical>;