Search code examples
cssweb-componentcustom-element

CSS pseudo :dir(); :host-context() and directionality based styling


In this question I'm looking for the cleanest possible solution for the problem below, along with urging the browsers' coders to catch up with the spec, especially :dir() one!!

The problem and it's current best known to me solution:

I'd like to style the image below based on directionality, flipping it, for example, when in RTL mode. The image resides in a shadow DOM. As of now, I'm achieving that with the styling below.

::shadowRoot
    <style>
        .directed-image:dir(rtl) { transform: rotateY(180deg); }    -- Firefox only as of now
        :host-context([dir=rtl]) { transform: rotateY(180deg); }    -- Chromium only as of now
    </style>

    <img class="directed-image" src="..." />

Issues yet to be solved:

  • None of the styles above helping Safari: it has not yet implemented :dir() pseudo class and it's people seems to have a strong objection to :host-context()
  • I'm really not fan of those double-done solutions for a platform's diversity; would like to get rid of those, but this is only a secondary concern

Solutions ?:

The best I'd wish to have is that :dir() will get wide cross browser support - it'll solve the Safari's issue as well as would provide a truly directionality context aware styling (downsides of [dir=ltr] are touched a bit in the WebKit's bug link above).

But given that

-- having all this: is there any other solution for the problem (looking to solve the Safari issue at first priority).

JS based solutions are interesting but much less preferred.


Solution

  • january 2020 answer:

    As you said: the dir attribute on the body tag will (in most cases) be the only indication of a language change. Since CSS doesn't cascade (yet; as you said) the only option for now is for Elements to observe that attribute change. So I fear your only option is a MutationObserver (in the elements you own)

    https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

    // Options for the observer (which mutations to observe)
    const config = { attributes: true, childList: false, subtree: false };