Background center with chrome (bug)

2019-03-16 06:14发布

I have a background image centered that Chrome displays offset by one pixel.

CSS

#container { 
    background: url("images/header.jpg") no-repeat scroll 50% transparent;
    width: 100%
}
#header {
    width: 986px;
    margin: 100px auto 0 auto;
}

HTML

<html>
<body>
    <div id="container">
        <div id="header">centered content</div>
    </div>
</body>
</html>

I guess it has to do with how different browsers handle the center -or 50%- property of the background in CSS:

enter image description here

Is there a known (simple) hack or alternative method to fix this? Background container has to be 100% wide.

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-16 06:34

Is the image actually 986px? The easiest way I found to fix it is to make sure the width of the image is an even number.

Another thing you could do is add a 2px buffer (to keep the width an even number) in the background image to account for that shift. It shouldn't shift your image as viewed in the browser as long as you add a px to each side to keep it all even.

查看更多
虎瘦雄心在
3楼-- · 2019-03-16 06:37

For me, this did the trick:

@media screen and (-webkit-min-device-pixel-ratio:0) { 

html {
    margin-left: 1px;
}

}

I will post the link for this solution as soon as I find were I got it from a few days ago. In the same post, the guy said the problem was with odd or even number for container width. Anyway, this fixed the problem in my case.

查看更多
Evening l夕情丶
4楼-- · 2019-03-16 06:39

I suppose the backgroud image is also 986 pixels wide? Then this effect should also be visible on the left side, turned around though.

I suggest to remove the background image from the container and add it to the header:

#container {
    width: 100%;
}
#header {
    width: 986px;
    background: url("images/header.jpg") no-repeat scroll 50% transparent;
    margin: 100px auto 0 auto;
}
查看更多
干净又极端
5楼-- · 2019-03-16 06:47

Try resizing the browser to see how it works... we are talking about pixels here, and if the window has a even width it's ok, otherwise a pixel has to be lost somewhere i guess.

查看更多
在下西门庆
6楼-- · 2019-03-16 06:51

If you can output your image wider than the browser window, that should fix it.

If found that solution here - http://philfreo.com/blog/fixing-safaris-1px-background-image-centering-problem/

查看更多
家丑人穷心不美
7楼-- · 2019-03-16 06:55

If you make the background image width an odd number (987px) the positioning will be consistent across all browsers. It seems counter-intuitive but that seems to always fix the issue for me without any CSS hacks.

查看更多
登录 后发表回答