Question

In the following MWE, a span and a div are placed inside an RTL div, and their order is swapped in Firefox but not in Chrome (no idea what it shows in IE...).

<html>
<body>
  <div dir="rtl">
    <span id="empty-span"></span>
    <div>This is arabic!</div>
  </div>
  <script>
    var anchorEl = document.getElementById('empty-span');
    var anchorRect = anchorEl.getBoundingClientRect();
    console.log(anchorRect);
  </script>
</body>
</html>

Firefox places the span to the right of the div, while Chrome keeps it to the left. (The exact value shown in the console depends on your screen size.)

Firefox:
  ClientRect {left: 700, right: 700, ...}
Chrome:
  ClientRect {left: 8, right: 8, ...}

I need the Firefox behavior, because the span is the target of a tooltip that should be placed near the text. I'm fairly new to web development, so what is the best approach: use another type of hidden element to anchor the tooltip, place the span differently depending on the browser, or what?

Just for clarity, there's no dir="rtl" attribute in fact, but the problem shows in Arabic and Hebrew locales. I just used it so people won't need to change their default language to reproduce.

Was it helpful?

Solution

In my opinion, handling of the dir attribute isn't especially well specified, which could explain why different browsers handle your situation differently. I'm guessing that since your <span> element is empty, and since it is retaining its default display property of inline, it no defined dimensions on the page. Chrome is optimizing by simply not bothering to apply the rtl formatting to it. When you change the display property to inline-block, you're giving the <span> a height and width, albeit 0. Chrome is "smart" enough to optimize when the element has no height and width defined, but it doesn't go the extra step of optimizing when the element has a defined height and width of 0. That's just a guess, though.

FWIW, I've found the CSS direction property to be more reliable than the dir attribute.

OTHER TIPS

In the end, the simplest solution for this case is to use a <span> instead of a <div> as the second element. Still not clear why the browsers have different properties.

Applying display:inline-block to both elements is overkill, but may be necessary if there are more elements that may need to flow through the parent <div>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top