csscss-selectorsattributespseudo-elementroot-element

In CSS, how do I conditionally style the :root pseudo-element using attributes?


I have some JS which needs to effect some styling of an entire rendered HTML document. What I current use is the following CSS:

[myattr="true"]  { direction: rtl; }
[myattr="false"]  { direction: ltr; }

plus setting an attribute on the document element:

doc.documentElement.setAttribute('myattr', true);

but - for reasons (which should not be relevant), I want the CSS to style the :root pseudo-element, not the <html> element. My question is: How can I select :root based on the attribute value? It's not as though I can set the attribute on :root itself, as it is not part of the DOM.


Solution

  • In an HTML document, the CSS :root selector represents the <html> tag, which is the root of the HTML document (MDN).

    Any attribute you set on the HTML element be can used to select the :root element as well:

    :root[myattr="true"] { 
      background: red;
    }
    <html myattr="true">
    
    </html>