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.
html[myattr=“false”] {
direction: ltr;
} This will work correctly. 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 Correct and works
Set attribute on document.documentElement () 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.