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.

document.documentElement.setAttribute(‘myattr’, ‘true’);
In CSS:

css
Copy
Edit
html[myattr=“true”] {
direction: rtl;
}

html[myattr=“false”] {
direction: ltr;
}
:white_check_mark: This will work correctly.
:white_check_mark: It effectively styles the :root (because html == :root).

If you absolutely must use :root somehow:
You can still do this (although it doesn’t change much):

css
Copy
Edit
:root {
/* default styling */
}

html[myattr=“true”] {
direction: rtl;
}

html[myattr=“false”] {
direction: ltr;
}
Notice:

:root sets default rules globally.

html[myattr=“…”] overrides or modifies based on attributes.

TL;DR

Your Wish Reality
Style :root based on an attribute Not possible directly
Style html based on an attribute :white_check_mark: Correct and works
Set attribute on document.documentElement () :white_check_mark: Correct
Quick Important Point:
The :root and html are the same element.
:root just gets higher specificity than html in CSS. That’s its main difference.

Final Example:
html
Copy
Edit

:root { --text-color: black; } html[myattr="true"] { direction: rtl; --text-color: red; } html[myattr="false"] { direction: ltr; --text-color: green; } body { color: var(--text-color); } Hello World