Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have simple div tag, absolutely positioned within an HTML doc. When in Chrome I set its "right" CSS rule to a fixed value in pixels, and its "left" rule to "auto", and then immediately afterwards determine its left position using jquery's position() method, the value returned is something of this kind: 122.6363525390625. The same goes for the offset() method.

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

Can you tell me why this happens and if there's a way to prevent it? Thanks in advance!

like image 229
Andrei Oniga Avatar asked Jun 22 '12 06:06

Andrei Oniga


People also ask

What is the difference between position and offset?

The offset() method retrieves the current position relative to the document, whereas the position() method retrieves the current position of an element relative to the parent element.

What is the difference between position and offset in jQuery?

Difference between offset() and position() Method:The jQuery UI offset() is relative to the document. The jQuery UI position() is relative to the parent element. When you want to position a new element on top of another one which is already existing, its better to use the jQuery offset() method.

What is offset () top in jQuery?

jQuery offset() Method The offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.

What is offset () Top?

The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element. the top padding, scrollbar and border of the parent.


1 Answers

Because when you use percentage widths that's what the math works out to. Imagine that you have this layout:

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

The inner element's width calculates to 55.5 pixels, not a natural number. Depending on the exact CSS attributes this could easily work out to quite a few more decimal places.

Chrome uses subpixel rendering, so that's why you see this behavior.

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

like image 70
Jon Avatar answered Sep 26 '22 19:09

Jon