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.