我想知道是否可以组合应用于同一元素并包含相同样式的 2 个规则,但其中一个规则位于媒体查询中并得到类似于以下内容的内容:
.a,
.b .a {
color: white;
background-color: black;
}
规则是:
prefers-color-scheme 将颜色应用于 .content,input 为 checked 时,更改 .content 颜色
:root {
--dark-color: white;
--dark-bg: black;
--light-color: black;
--light-bg: white;
}
@media (prefers-color-scheme: dark) {
.content {
color: var(--dark-color);
background-color: var(--dark-bg);
}
}
#dark-theme:checked~.content {
color: var(--dark-color);
background-color: var(--dark-bg);
}
@media (prefers-color-scheme: light) {
.content {
color: var(--light-color);
background-color: var(--light-bg);
}
}
#light-theme:checked~.content {
color: var(--light-color);
background-color: var(--light-bg);
}
<input type="radio" name="color-theme" id="dark-theme"> <label for="dark-theme">dark</label> <input type="radio" name="color-theme" id="light-theme"> <label for="light-theme">light</label> <input type="radio" name="color-theme" id="default-theme" checked> <label for="default-theme">default</label> <div class="content">Test</div>
如果 prefer-color-scheme 为深色,或者选中 #dark-theme,则此处 .content 将获得黑色背景和白色。
这两个规则应用相同的样式。
有没有办法结合这些规则?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
:root { --dark-color: white; --dark-bg: black; --light-color: black; --light-bg: white; } @media (prefers-color-scheme: dark) { #default-theme:checked~.content { color: var(--dark-color); background-color: var(--dark-bg); } } #dark-theme:checked~.content { color: var(--dark-color); background-color: var(--dark-bg); } @media (prefers-color-scheme: light) { #default-theme:checked~.content { color: var(--light-color); background-color: var(--light-bg); } } #light-theme:checked~.content { color: var(--light-color); background-color: var(--light-bg); }你无法使用原生 CSS 来做到这一点。但是,如果您的问题与减少编写有关,那么 CSS 编译器已经满足了这种需求。 如果你愿意尝试,这是用 Sass 编写的简单代码。
首先,您可以将内容包装在
@mixin中。它将使用一个变量存储您的类,该变量应根据所选主题进行更改。@mixin content-style($theme) { .content { color: var(--#{$theme}-color); background-color: var(--#{$theme}-bg); } }之后,您可以在另一个 mixin 中使用它来定义主题样式:
@mixin themed-style($theme) { @media (prefers-color-scheme: $theme) { @include content-style($theme); } ##{$theme}-theme:checked ~ { @include content-style(#{$theme}); } }最后,您可以使用它来创建尽可能多的主题,只需更改变量即可:
如果您想查看与原始代码相同的输出,可以此处尝试
复制粘贴完整代码以查看转换:
:root { --dark-color: white; --dark-bg: black; --light-color: black; --light-bg: white; } @mixin content-style($theme) { .content { color: var(--#{$theme}-color); background-color: var(--#{$theme}-bg); } } @mixin themed-style($theme) { @media (prefers-color-scheme: $theme) { @include content-style($theme); } ##{$theme}-theme:checked ~ { @include content-style(#{$theme}); } } @include themed-style(dark); @include themed-style(light);