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

后端 未结 1 1243
予麋鹿
予麋鹿 2021-02-20 06:19

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

相关标签:
1条回答
  • 2021-02-20 07:18

    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>
    
    0 讨论(0)
提交回复
热议问题