We typically use value cover or contain to size image such as background-size: cover | contain;, object-fit: cover | contain; but if you have any confusion what it does or how it works, this article got you covered (pun intended 😅).

cover and contain

  • Both maintain image aspect ratio
  • cover make sure that entire container is covered by image, leaving no empty spaces. This may result in cropping img
  • contain make sure entire image fits inside container without any cropping, thus ensures entire image is visible or contained within the container. This may result of having empty space inside container.

Image description

So in short,

Image description

If want to dig deeper on how it works, I have got you covered.

cover and contain logic

  • In both cases, browser compares aspect ratio of image and container
  • aspect ratio = width / height

cover

if (aspect ratio of container > aspect ratio of image)
    image-width = container width
    image-height = aspect-ratio-preserved height

else
    image-height = container height
    image-width = aspect-ratio-preserved width

contain

if (aspect ratio of container > aspect ratio of image)
    image-height = container-height
    image-width = aspect-ratio-preserved width

else
    image-width = container width
    image-height = aspect-ratio-preserved height

Source: stack overflow

So if you ever wondered as to why in CSS value cover, sometimes image width is equal to container width and sometimes image heigh is equal to container height, this is how browser decides if image width or heigh should be used to cover the container. Same goes for contain.