Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement