The background image, moving partially from the window, if specified with the background position: center;

I have the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="1.css">
</head>
<body>

<body>

My CSS code is as follows:

body {
    background-image: url(tree.png);
    background-repeat: no-repeat;
    background-position: center;
}

My Chrome browser now displays the following output:

enter image description here

Here the image tree is on top and partially outside the window.

To fix this, I change my CSS code to the following:

body {
        background-image: url(tree.png);
        background-repeat: no-repeat;
        background-position: center;
        margin-top: 600px;
    }

Now my browser shows the following output:

enter image description here

My question is why should I add margin at the top and the default background-image will not be in the center of my browser page?

+4
source share
2 answers

This is due to the height of the document. Without content, body height is minimal. If you change your CSS to the following, the background image should be central:

html {
    background-image: url(tree.png);
    background-repeat: no-repeat;
    background-position: center;
    height:100%;
}

https://jsfiddle.net/z85ony88/

, . :

html {
  height:100%;
}
body {
    background-image: url(https://jsfiddle.net/img/logo.png);
    background-repeat: no-repeat;
    background-position: center;
}
+3

- , . , , . . height: 100vh, , .

body {
  background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg);
  background-position: center;
  background-repeat: no-repeat;
  height: 100vh;
}
<body>

</body>
+2

Source: https://habr.com/ru/post/1685430/


All Articles