Hacker News new | past | comments | ask | show | jobs | submit login
Background-image is not in proportion with element?
2 points by shivajikobardan on Nov 9, 2022 | hide | past | favorite | 2 comments
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.

https://imgur.com/a/nBFakLW

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?*




300 * 500 and 2000 * 2500 have different aspect ratios (0.6 and 0.8). Because you used background-size: cover, the image was resized down in the same aspect ratio (to not stretch it), and cropped to fit the container, and your screenshot proves it.


thank you. I think I got it.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: