Search code examples
csscontainbackground-size

background-size: contain not showing the whole picture


I'm wondering why contain works like this. This is my HTML code.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Zero to Mastery | Landing Page</title>
  <link rel="stylesheet" type="text/css" href="landingPageStyle.css">    
</head>

<body>

</body>

</html>

Now, this is my CSS code:

body {
/* min-height: 100%;   */
width: 600px;
height: 600px;
border: 4px solid red;
background-image: url('Nature500x400.jpg');
background-size: contain;   
background-repeat: no-repeat;
}

My question is this: why is not the whole background picture inside the body? Why the picture exceed the border like in this picture of browser window:

https://i.sstatic.net/uDuzD.png


Solution

  • Applying the styles to html instead of body will fix this problem

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Zero to Mastery | Landing Page</title>
      <link rel="stylesheet" type="text/css" href="landingPageStyle.css">    
    </head>
    
    <body>
    
    </body>
    
    </html>
    

    Use html instead:

    html {
    /* min-height: 100%;   */
    width: 600px;
    height: 600px;
    border: 4px solid red;
    background-image: url('Nature500x400.jpg');
    background-size: contain;   
    background-repeat: no-repeat;
    }