Why when I set the width: 400px
and height: 400px
to <img>
, the image is exactly square, but when I use a <div>
to then apply a background-image
to it and set same width: 400px
and height: 400px
there, the picture is disproportionate, and only if I set width: 1600px
and height: 400px
, then it becomes square? How to set the background-image
size correctly so it becomes square, just as <img>
?
I add this on background image, but it didn’t work:
background-position: center;
background-repeat: no-repeat;
background-size: cover;
width: 400px;
height: 400px;
Here’s my fiddle: https://jsfiddle.net/vwe6hsn9/6/ (try to comment the width & height, the image disappears).
I would also like to have a background-color
in case the image won’t load for the user, so that he knows here should be a picture. But it’s also not visible if you remove the image.
2
Answers
I will answer as I understand it, because there are some “too smart people” in the comments who were unable to clearly explain and give their answer here.
background-size: cover;
it instructs the browser to scale the background image while maintaining its aspect ratio to cover the entire container. This can result in the image not being displayed in its original dimensions, causing distortion.background-size: 400px 400px;
without adding awidth
andheight
, becausebackground-image
, I'd suggest usingflex-shrink: 0;
, because is a way to preventbackground-image
from shrinking when its container is smaller than the size of thebackground-image
.So, if we want the
background-image
to be400x400
we can do the next:Hopes it helps someone!
I had the exact problem that you had, try giving these values to the img style so it fills the entire screen:
Please note that if you want to use a background image try these instead: