简体   繁体   中英

CSS background-position will not center

I am having trouble centering my background. Whether I change the BG into small size to make it center it won't.

Her is my CSS:

#container {    
    background-image: url(Photos/BG.png);
    background-repeat:no-repeat;
    background-position: center center;
    height: 1813px;
    width: 1024px;
}

It doesn't center the background - it keeps going to the top left of the monitor even though using a smaller size photo. Thank you all!

To centralise the background image you don't need to specify center center twice. It should be as follows:

 #container {    
    background-image: url(Photos/BG.png);
    background-repeat:no-repeat;
    background-position: center;
    height: 1813px;
}

Your code works as aspected, if you remove the width you will see exactly the image centered in the background...

<!DOCTYPE html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <style>
        #container {    
    background-image: url('http://supermario3dworld.nintendo.com/_ui/img/views/power-ups/char-dobble-mario.png');
    background-repeat: no-repeat;
    background-position: center; /* you dont need to specify the value two times */
    height: 1813px;

            background-color: aquamarine;
}
    </style>
</head>

<body>
    <div id="container">

    </div>
</body>
</html>
background-image: url(path-to-file/img.jpg);
background-repeat:no-repeat;
background-position: center center;

should work, one other thing you could do is make a div and put the img in it, then use -1 z-index and just center the div.

You could also try adding

body {
  min-height: 100%;
}

because the container might not be the full viewport size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM