Search code examples
javascripthtmlcsscustom-element

Custom Element returning incorrect offset when position is "relative:


Code: https://jsfiddle.net/q157xktz/1/

when the position of this custom element is set to relative, the offset displays correctly. For example, if the true offset is 0 it displays as 25. Why is this? The element in question is root-class-bubble


Solution

  • It is because by default your browser renders every unknown element as an inline element. All known HTML elements have default styles set by the user agent. Custom elements don't have any styles at all provided by the user agent, so you'll have to explicitly style every element that you create. So for example, adding display: block to the styles of your root-class-bubble element will solve the offset value.

    And to explain why the offset value differs I'm quoting this article from MDN, which explains how the offset properties differ with different element types. Starting with block-level elements.

    For block-level elements, offsetTop, offsetLeft, offsetWidth, and offsetHeight describe the border box of an element relative to the offsetParent.

    And with inline-level element:

    However, for inline-level elements (such as span) that can wrap from one line to the next, offsetTop and offsetLeft describe the positions of the first border box (use Element.getClientRects() to get its width and height), while offsetWidth and offsetHeight describe the dimensions of the bounding border box. Therefore, a box with the left, top, width and height of offsetLeft, offsetTop, offsetWidth and offsetHeight will not be a bounding box for a span with wrapped text.