Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why .offsetParent returns nearest table for non-positioned element

From the MDN documentation for Element.offsetParent:

The HTMLElement.offsetParent read-only property returns a reference to the object which is the closest (nearest in the containment hierarchy) positioned containing element. If the element is non-positioned, the nearest table, table cell or root element is returned by offsetParent

Why does .offsetParent return the nearest table if the element is not positioned (that is, position: static)? Why doesn't .offsetParent always return the nearest positioned element?

I know that the answer to my question is "because the standard says so," but why did the developers of the standard decide that? What is the purpose of that behavior?

like image 438
diralik Avatar asked Jul 05 '26 04:07

diralik


1 Answers

The docs were at best misleading, or mislead.

The new version is clearer:

A positioned ancestor is either:

  • an element with a non-static position, or
  • td, th, table in case the element itself is static positioned.

So, .offsetParent does "return the nearest positioned element", if there is one before the nearest td, th, or table:

console.log("in positioned", target1.offsetParent);
console.log("in static", target2.offsetParent);
.positioned { position: relative }
<table>
  <tbody>
    <tr>
      <td>
        <div class=positioned>
          <span id=target1>content</span>
        </div>
      </td>
      <td>
        <div class=static>
          <span id=target2>content</span>
        </div>
      </td>
    </tr>
  </tbody>
</table>

As for why they decided these elements should be treated as positioned elements even though their computed position is "static", it's certainly because their position is actually dictated by rules that doesn't match static's rules.

like image 172
Kaiido Avatar answered Jul 07 '26 17:07

Kaiido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!