Cody Cody - 28 days ago 9
CSS Question

background-position property unable to center the image

The following code is unable to place the image at the center of the screen.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
background-image: url("../images/dandelion.jpg");
background-repeat: no-repeat;
background-position: center center;
}
</style>
</head>
<body>


</body>
</html>


This is what I am getting.

enter image description here

Answer

Your body is only as tall as the things inside it, so its actually centering correctly.

To get the result you want, you need to either make the actual page longer by adding things to it, or this to work around:

html,body{ height:100%; }

Note that you need to have html in there too because percentage height is relative to its parent (<html> is a parent of <body> in this case)

Comments