How to tell where a horizontally centered element is exactly, if it is not precise in Chrome?

为君一笑 提交于 2019-12-12 02:26:43

问题


A picture and a fiddle is worth more than a thousand words:

http://jsfiddle.net/xrer55r7/

Slowly resize the window and see the striped background mis-aligned every now and then. I'm logging the position in the console, which doesn't change at all. Visually it does, though.

Chrome aligns a horizontally centered element (with text-align: center;) in another horizontally centered element (with margin: 0 auto;) in a way that it rounds the apparent position, resulting in a visual change. It is not reflected in the position I get for the element using jQuery's .position().

Bascically the problem is not present in Firefox/Safari, is there to some extent on IE (in my application it doesn't cause a problem), but it is very prominent on Chrome.

I need a way to get or calculate this position OR to disable this behavior OR a workaround for the background to not misalign while keeping everything centered.

<div class="box">
    <div class="centered good">
        This is just fine! :)
    </div>
    <br/>
    <div class="centered bad">
        This is not :(
    </div>
</div>

<script type="text/javascript">
    .box {
        width: 313px;
        height: 206px;
        background: url('data:image/gif;base64,R0lGODlhAgABAIAAACmd/////ywAAAAAAgABAAACAkQKADs=');
        position:relative;
        margin: 0 auto;
        text-align: center;
    }
    .centered{
        display: inline-block;
        color: black;
        padding: 5px;
        background: url('data:image/gif;base64,R0lGODlhAgABAIAAACmd/////ywAAAAAAgABAAACAkQKADs=');
        font-size:15px;
    }
</style>

来源:https://stackoverflow.com/questions/25505916/how-to-tell-where-a-horizontally-centered-element-is-exactly-if-it-is-not-preci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!