Search code examples
csscontainsbackground-size

Why doesnt background-size: contain work in this case?


I don´t understand why in this specific case, the property background-size: contain doesnt work. In this case changing background-size: contain for background-size: cover does work! Why?

Here my codepen: https://codepen.io/JMainol/pen/eYpbQyg

html

<body>

</body>

css

body{
margin: 0;
padding: 0;
background:   url(https://lh3.googleusercontent.com/proxy/-6w3o1Xo04RZwWw86XzQ7TakArUKvRGUF0l-2o25my6y8W47rSTqjOyfVYEg8qZPgkzbQAEoBZQfyiQ-0Hpm72MIRTeCjeUhxtBKt1fenboarbMxo3TrU5cBdbRfvav1377ZearzLWB2ds6_uT_KJs2lKPYo3GxSkYj84XqG5c6JK_2-6MDiSOC8i6KecAopJQ);
background-repeat: no-repeat;
background-size: contain;

}


Solution

  • Very good question. The contain attribute is used only where there is an area that has relatively defined proportions to the image. Contain attribute scale the image as large as possible without cropping or stretching it.

    While the cover attribute is used when the image can be stretched to any proportion, hence the html body tag has unlimited proportions (height and width), it can really vary a lot. If the proportions of the image differ from those of the element, it is cut vertically or horizontally so that there is no empty space.

    To illustrate my explanation, I added 2 more lines to the css you provided.

    body{
      width: 1920px;
      height: 1080px;
        background: url('https://lh3.googleusercontent.com/proxy/-6w3o1Xo04RZwWw86XzQ7TakArUKvRGUF0l-2o25my6y8W47rSTqjOyfVYEg8qZPgkzbQAEoBZQfyiQ-0Hpm72MIRTeCjeUhxtBKt1fenboarbMxo3TrU5cBdbRfvav1377ZearzLWB2ds6_uT_KJs2lKPYo3GxSkYj84XqG5c6JK_2-6MDiSOC8i6KecAopJQ') no-repeat center;
        background-size: contain;
    }
    

    When height and width proportion are added, the image size adjusts according to the "Contain" attribute. But when there is no height and width, the Contain attribute does not have any effect.