What happens in background-size:cover when background-image is not in proportion with element?

I’ve 2000 * 2500 image.

I’m learning about background-size property. Currently about cover.

cover:

Scales the image (while preserving its ratio) to the smallest possible size to fill the container (that is: both its height and width completely cover the container), leaving no empty space. If the proportions of the background differ from the element, the image is cropped either vertically or horizontally.

Source: MDN Docs

I want to focus on that bold part.

HTML:

<div class="first-div"></div>

CSS:

.first-div {

height: 500px;

width: 300px;

background-image: url(img1.jpg);

background-size: cover;

}

The image is named “img1.jpg”.

https://imgur.com/a/vrzGZ2P

This is the image. Source: pexels.com

I expected huge part of image to be cut down since my div is only 300 * 500 whereas my image is 2000 * 2500. But it didn’t happen.

Something like this happened:

Why did this happen?

Was the image resized w/o losing aspect ratio? Should not then, it should try to fit the div? What algorithm is being used here in this case?

The behavior seems to be correct. Take a look at my repro:

You can see that the div is 300x500, and the image appears inside it with no wasted space.

1 Like