skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    1. 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.
    2. As @Brett Donald mentioned, we can't just use background-size: 400px 400px; without adding a width and height, because

    when 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

    1. Also, if you have any element (for example text) next to the element that contains a background-image, I'd suggest using flex-shrink: 0;, because is a way to prevent background-image from shrinking when its container is smaller than the size of the background-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;
    

    Hopes it helps someone!


  2. I had the exact problem that you had, try giving these values to the img style so it fills the entire screen:

        background-size: 400% 400%;
        height: 100%;
        margin: 0;
        background-repeat: no-repeat;
        background-attachment: fixed;
    

    Please note that if you want to use a background image try these instead:

      background-image: url('your-path');
      background-size: 400% 400%;
      height: 100%;
      margin: 0;
      background-repeat: no-repeat;
      background-attachment: fixed;
      background-size: cover; 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search