42
loading...
This website collects cookies to deliver better user experience
:root {
--primary-color: #2e3a59;
}
html {
color: var(--primary-color);
}
:root.other-theme {
--primary-color: #8f9bb3;
}
prefers-color-scheme
.@media (prefers-color-scheme: dark) {
}
@media (prefers-color-scheme: dark) {
:root {
filter: invert(100%);
}
}
@media (prefers-color-scheme: dark) {
:root,
:root img {
filter: invert(100%);
}
}
:root
and reverse visual elements to their initial state?”. Why can’t we just write the following CSS code:*:not(img) {
filter: invert(100%);
}
<div>
<p>
Text in p
<span>and in span.</span>
</p>
With picture of me:
<img src="./pic.jpg" />
</div>
div
matches our selector, the filter will apply to it. As a result, everything will be negative.p
is inside the div
, it matches the selector and will change too. Thus, we will have it reinverted so that the colors get back to normal.span
also matches the selector. Whereas the p
has become normal, the contents of the span
went negative.img
selector is not influenced by the filter, so no inversion happens. However, as the img
is a part of the element that we have inverted, the image will be negative.root
element once. Then, we invert the elements that we want to stay the same, again to bring them to the initial state.select
to the header of our app, allowing users to choose the theme they prefer. The select will include 3 choices: light
, dark
, and auto
.auto
will be a default value that will allow the app to inherit system settings. At the same time, when choosing light
or dark
, we are adding a theme-light
or theme-dark
class correspondingly to the root
element of a document. Then, we delete a theme class if using auto
. To top it off, we save these settings in localStorage
, which allows us to show the previous theme.@media screen and (prefers-color-scheme: dark) {
:root:not(.theme-light):not(.theme-dark),
:root:not(.theme-light):not(.theme-dark) img {
filter: invert(100%);
}
}
:root.theme-dark,
:root.theme-dark img {
filter: invert(100%);
}