Cody
Cody

Reputation: 2649

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

Upvotes: 1

Views: 133

Answers (4)

No one
No one

Reputation: 1140

Give html and body height 100% and background position 50% 50% or center center.

html {
    height: 100%;
}
body{
    background-image: url("http://i.imgur.com/InDshke.png");
    background-repeat: no-repeat;
    background-position: 50% 50%;
    height: 100%;
}

Upvotes: 0

Graham Shroll
Graham Shroll

Reputation: 291

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)

Upvotes: 2

Saurav Rastogi
Saurav Rastogi

Reputation: 9731

Checkout this Fiddle (jsFiddle).

You need to reset default properties and give these some styles as your containers such as <html> and <body> are adjusted according to the content inside it (in this case the image).

Apply these styles:

html, body {
  width: 100%;
  height: 100%;
}

body {
  margin: 0;
  background-image: url("http://placehold.it/200x200");
  background-repeat: no-repeat;
  background-position: center center;
}

Hope this helps!

Upvotes: 0

Rahul
Rahul

Reputation: 4374

u may want to try something like this fiddle

body{
  background-image: url("http://i.imgur.com/InDshke.png");
  background-repeat: no-repeat;
  background-position: center -25%;
  background-size: 50%;
  height: 100%;
  width:100%;
}

Upvotes: 0

Related Questions