Click here to Skip to main content
15,881,413 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
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:

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

CSS:

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: copyright free image from 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?

What I have tried:

I've tried looking at devtools and aspect ratio was 4:5 there for the image. 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?
Posted
Updated 9-Nov-22 15:17pm

1 solution

Watch this video as it goes into depth on this topic: Kevin Powell - Background images with HTML & CSS - YouTube[^]

Kevin Powell is a well-respected professional and teacher. Do check out his other videos.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900