Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - .position isn't returning offset relative to parent

Tags:

jquery

css

I'm using .position to find the offset of where the element is relative to the parent, however it seems to be returning a value that is the offset from some parent up the ancestor tree.

I have a button, and its wrapped withing a div and its the only element of that div. The div is floated right. .position is returning a value like {left:780, top:370}, when the true value should be around {left:200, top:0}.

I'm using jquery 1.4

like image 871
Kyle Avatar asked May 16 '10 02:05

Kyle


1 Answers

If I am correct, I think this is a CSS issue, not necessarily a jQuery one.. My understanding is that the default value of the CSS "position" property is static (not absolute, relative), and positioning is calculated relative to the first ancestor that is not set to static.

If the element has no ancestor with non-static position, the element will be positioned relative to the html block.

If you want to position a div relative to a wrapper div, try setting the wrapper div's position property to something other than static (relative, absolute), depending on your needs.

Here's a simple example that demonstrates this..

<html>
  <style type="text/css">
    .divOuter { border:1px solid Green;  width:350px; height:50px; padding:2px; margin-left:80px; }
    .divInner{border:1px solid Blue;  width:200px; height:50px; padding:2px; position:absolute; left:100px;}
 </style>
 <body>
 <div class="divOuter">
  <div  class="divInner">
     positioned relative to html block 
  </div>
  </div>
      <div  class="divOuter" style="position:relative;">
   <div class="divInner">
     positioned relative to parent div
  </div>
  </div>
  </body>
  </html>
like image 142
markt Avatar answered Nov 04 '22 03:11

markt