4

I'm trying to create a page with a centered background image and using the position center center. But instead of appearing centered both vertically and horizontally the image appears to extend vertically beyond the top of the page. Where/why am I going wrong?

<!DOCTYPE html>
<html>
<style>
body
{
background-image:url('tumbleweed.jpg');
background-repeat:no-repeat;
background-position:center center;
background-color:#EAEAEA;
}
</style>
</html>
Sally
  • 43
  • 1
  • 1
  • 3

5 Answers5

6

Would you see the screen like below picture?

enter image description here

body{
  background-image:url(../IMG/BG/pizzaBackground.jpg);
  background-size: cover;
  background-position: 50% 50%;
  background-repeat: no-repeat;
}

I think It's because you didn't declare 'height'.

Add 'height:100vh'style.

body{
  height: 100vh;    /* ADD STYLE ! */
  background-image:url(../IMG/BG/pizzaBackground.jpg);
  background-size: cover;
  background-position: 50% 50%;
  background-repeat: no-repeat;
}

The reason for setting to 100vh is because the target is body tag.

If it's a different tag, use a different value.

Then this will be

enter image description here

And add 'margin:0px' style to remove the scroll.

body{
  margin: 0px;     /* ADD STYLE ! */
  height: 100vh;
  background-image:url(../IMG/BG/pizzaBackground.jpg);
  background-size: cover;
  background-position: 50% 50%;
  background-repeat: no-repeat;
}

Then you can see

enter image description here


Thanks!

KimYC1223
  • 61
  • 1
  • 4
2

You can use cover

background-image:url('tumbleweed.jpg');
-webkit-background-size: cover;
-moz-background-size: cover;
 -o-background-size: cover;
 background-size: cover;

http://jsfiddle.net/ou10gmfd/

Stacker-flow
  • 1,251
  • 3
  • 19
  • 39
2

Try this:

background-position: 50% 50%;

Or maybe you should try a space before the first center (could be an issue).

koenest
  • 29
  • 1
0

Most likely this is because your image is to large use background-size: cover; to cover the whole background of the body

-2

remove DOCTYPE html from your page and it will work fine. or use background-attachment: fixed;. then you do not have to remove DOCTYPE html

  • The browser may automatically go into Quirks or Strict Mode when DOCTYPE is not present on the page. see https://stackoverflow.com/q/23230798/1363169 for insight. – kplus Jun 30 '21 at 18:41