Why do jQuery position () and offset () methods return a fractional number in Chrome?

I have a simple div tag absolutely positioned in an HTML document. When in Chrome I set my “correct” CSS rule to a fixed value in pixels and its “left” rule to “automatically” and then immediately determine its left position using the jquery position () method, the return value is something like this view: 122.6363525390625 . The same goes for the offset () method.

Firefox, on the other hand, does not have this problem.

Can you tell me why this is happening and is there a way to prevent this? Thanks in advance!

+8
jquery css google-chrome
source share
2 answers

Because when you use the percentage widths that math comes from. Imagine you have this layout:

<div style="width: 111px"> <div style="width: 50%"></div> </div> 

The internal width of an element is calculated to 55.5 pixels, not a natural number. Depending on the exact CSS attributes, this can easily work out a few more decimal places.

Chrome uses subpixel rendering , so you see this behavior.

Finally: I'm not sure why this will cause you problems, but of course, if you want to round to a natural number, you can use Math.round(x) .

+10
source share

In Chrome, values ​​are truncated, so 120, 120.5, and 120.6 all have the same width, so you don’t have to worry about that using a decimal value. There is nothing better than .5 pixels. A pixel is whole units. If you have this problem of functions that return a decimal value, then why not use parseInt? You should not leave this thing in the browser to take care, otherwise your page may break.

-2
source share

All Articles