I have a dynamic class which is applied on html tag when user presses the button to switch view to dark mode:
<html lang="en" class="app-dark-theme">
Now in child Angular component I need to check if this class exists on html tag to style one particular class in this child component.
How can I achieve this? I tried :has()
pseudo-selector but it didn't work for me.
html:has(.app-dark-theme) {
.test-class {
border: 1px solid var(--p-blue-200);
}
}
Preferable solution is pure CSS/SCSS if possible.
Thanks.
The issue is most likely caused by Angular Style scoping.
By default, Angular uses emulated encapsulation so that a component's styles only apply to elements defined in that component's template. In this mode, the framework generates a unique HTML attribute for each component instance, adds that attribute to elements in the component's template, and inserts that attribute into the CSS selectors defined in your component's styles. See more in Angular docs
Consequently, the following component style
html.app-dark-theme {
.test-class {
border: 1px solid var(--p-blue-200);
}
}
results in something similar to
// _ngcontent-ng-c2903067727 is the unique HTML attribute added by Angular
// It is not specified on the html element so the CSS rule doesn't match anything
html.app-dark-theme[_ngcontent-ng-c2903067727] .test-class[_ngcontent-ng-c2903067727] {
border: 1px solid var(--p-blue-200);
}
To get around that, the Angular docs suggest to use :host-context()
in your component styles
:host-context(html.app-dark-theme) {
.test-class {
border: 1px solid var(--p-blue-200);
}
}