How to Make Your Images Responsive

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.

css
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.

css
1img {
2  max-width: 50vw;
3  aspect-ratio: 1/1;
4}

aspect ratio

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.
css
1img {
2  max-width: 50vw;
3  aspect-ratio: 1/1;
4  border: 2px solid black;
5
6  object-fit: fill;
7}

object fit fill

  • contain keeps the image's original dimension and resizes the image to fit the space.

object fit contain

  • cover keeps the image's original dimension, and resizes and crops the image to fill the space.

object fit cover

  • none keeps the image's original dimension and size.

object fit none

  • scale-down keeps the element's original dimension and scales the image down to fit the space. Unlike contain, if the image is smaller than the defined space, it will not be scaled up to fit the space.

object fit scale down

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:

text
1object-position: <horizontal_position> <vertical_position>;

For example,

css
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}

object position

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.