Issue
Why is it that when I set both the <img>
's width and height to 400px, the image is exactly square, but when I use a <div>
to then apply a background-image
to it and set the same size 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 added this to 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 out 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 they know here should be a picture. But it's also not visible if you remove the image.
Solution
When we set
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.As @Brett Donald mentioned, we can't just use
background-size: 400px 400px;
without adding awidth
andheight
, becausewhen you remove the width and height of your div, it disappears because it is empty; it doesn't contain anything; it shrinks to a size of zero width and zero height
Also, if you have any element (for example text) next to the element that contains a
background-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 be 400x400
we can do the next:
background-position: center;
background-repeat: no-repeat;
background-size: cover; // or background-size: 100% 100%, depending on what you need.
width: 400px;
height: 400px;
Answered By - Michael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.