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:55

I used the following bit of CSS to fix the problem on webkit. If JS isn't enabled, it works on the assumption that the browser will probably be full screen, so the viewport width on webkit will be an odd number

CSS

@media screen and (-webkit-min-device-pixel-ratio:0) { 
    html {
        margin-left: 1px;
    }
    html.evenWidth {
        margin-left: 0px;
    }
}

JavaScript (jquery)

$(document).ready(function {
var oWindow = $(window),
htmlEl = $('html');

function window_width() {
    if(oWindow.width() % 2 == 0) {
        htmlEl.addClass('evenWidth');
    } else {
        htmlEl.removeClass('evenWidth');
    }
}

$(document).ready(function(){
    window_width();
    $(window).resize(window_width);
});
查看更多
登录 后发表回答