简体   繁体   中英

Misalignment between centered Background image and centered DIV depending on browser width

I have a background image with a square which has the same size as a div that is covering this square. (There is a god reason for this not mentioned here). When centering this background image and the div, they do not overlap on certain browser width's. When re-sizing the browser, sometimes the background square is misaligned by 1 pixel. As you can see in the example below and in the JSFiddle, 1 pixel of the background square is visible sometimes when dragging the width of the browser.

Is there a solution for this? Why is the positioning between the elements not synced?

在此处输入图片说明

Try to re-size the fiddle-view-port width and you will see that the cyan background-square sometimes is visible when the misalignment occur.

JSFiddle: http://jsfiddle.net/jj3qxL3k/

Code:

    <div>CONTENT DIV</div>

CSS

    div{
        background-color: yellow;   
        width: 800px;
        margin: 0 auto;
    }
    html{
        background: url(http://s29.postimg.org/42cuy8m7b/tester.png) center center repeat;
        margin: 0;
        padding: 0;    
    }
    body{
        margin: 0;
        padding: 0;
    }

在此处输入图片说明

Tried this without any luck:

    /* Fix form centering background input chrome */
    @media screen and (-webkit-min-device-pixel-ratio:0) {
        html {
            margin-left: 1px;
        }
    }

    @media screen and (-webkit-min-device-pixel-ratio:0) {
        body {
            background-position: 50.001% 0;
        }
    }

By the way... This happens for me in Chrome Version 43.0.2357.81 m.

This depends on how the browser handles uneven values and aligns backgrounds and content.

This happens when your container has an odd width value since your element inside the container has an even width value. For example if your element is 800px wide and the container is 855px wide then there would be 855-800 = 55px of space left around your element and now the browser has to divide that for the two sides. It would come down to 22.5 pixels per side but since it can't paint half a pixel it has to round the number. So one side of the element would get 23px and the other side 22px.

Now it could be argued that the background image itself is treated the same way so the alignment should be the same, but in fact this is solely up to how the browser is built so that's why you are getting different results in different browsers.

It's rather hard to suggest a workaround without seeing the actual project since it would probably have to be a different solution all together.

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