By default, the images embedded in the webpage will be displayed in a pixel-to-pixel manner, with one image pixel matching one viewport pixel, which means the image will likely be either too large or too small for the current viewport. For an image to be displayed properly on any device, you should define a size with a relative unit such as %
or vw
.
1img {
2 max-width: 50vw;
3}
Sometimes, an image must be displayed with a fixed aspect ratio. For example, a profile avatar usually has a 1:1 aspect ratio, but the images might come in different sizes, especially for user-uploaded images. If you only define an aspect-ratio
property, the image will be stretched or squished.
1img {
2 max-width: 50vw;
3 aspect-ratio: 1/1;
4}
In this case, you can use the object-fit
property to specify how the image should be displayed in the defined space.
- The default option,
fill
, will stretch or squish the image to fit the given dimension.
1img {
2 max-width: 50vw;
3 aspect-ratio: 1/1;
4 border: 2px solid black;
5
6 object-fit: fill;
7}
contain
keeps the image's original dimension and resizes the image to fit the space.
cover
keeps the image's original dimension, and resizes and crops the image to fill the space.
none
keeps the image's original dimension and size.
scale-down
keeps the element's original dimension and scales the image down to fit the space. Unlikecontain
, if the image is smaller than the defined space, it will not be scaled up to fit the space.
In order to use the image as a profile avatar, it is best to set object-fit
to cover
. Because it will not change the image's aspect ratio, and the defined space will be completely filled.
However, notice that the image is zoomed in on the center, which caused the cat's ear to be cropped off. In this case, you could adjust the position of the image using the object-position
property, which has the following syntax:
1object-position: <horizontal_position> <vertical_position>;
For example,
1img {
2 max-width: 50vw;
3 aspect-ratio: 1/1;
4 border: 2px solid black;
5
6 object-fit: cover;
7 object-position: 50% 10%;
8}
This CSS code lets the browser zoom in on the top portion of the image, putting the cat at the center of the defined space.