问题描述
所以我正在创建一个支持暗模式的网络应用.
So I am creating a web app that supports dark mode.
如果设备默认喜欢暗模式,它将通过媒体查询使用暗模式@media (prefers-color-scheme: dark)
.
If the device prefers dark mode by default, it will use the dark mode by the media query @media (prefers-color-scheme: dark)
.
但我也想有一个功能,用户可以通过给 body 添加一个属性来手动切换到暗模式:data-theme="dark"
.
But I also want to have a feature that users can manually switch to dark mode by adding an attribute to the body: data-theme="dark"
.
所以我尝试了这个:
// ...
.ChatScreen {
background-color: #eee;
}
@media (prefers-color-scheme: dark), body[data-theme="dark"] {
.ChatScreen {
background-color: #000;
}
}
它在编译时给我这个错误:
It gives me this error while compiling:
Failed to compile.
./src/scss/app.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneOf-5-3!./node_modules/sass-loader/dist/cjs.js??ref--6-oneOf-5-4!./src/scss/app.scss)
SassError: Invalid CSS after "...me: dark), body": expected "{", was '[data-theme="dark"]'
on line 107 of src/scss/screens/_chat.scss
from line 6 of /Users/****/src/scss/app.scss
>> @media (prefers-color-scheme: dark), body[data-theme="dark"] {
-------------------------------------^
如何在不重复这些代码的情况下实现这一目标?
How can I achieve this without duplicate these codes?
推荐答案
@media (prefers-color-scheme: dark) {
body {
&[data-theme="dark"] {
.ChatScreen {
background-color: #000;
}
}
}
}
您可以查看 sass mixin 并定义您的深色样式,然后在您需要的任何地方包含该规则.
You can look at sass mixins and define your dark styling and then include that rule wherever you need.
编辑
@mixin dark-theme {
.ChatScreen {
background-color: #000;
}
}
@media (prefers-color-scheme: dark) {
@include dark-theme;
}
body {
&[data-theme="dark"] {
@include dark-theme;
}
}
这篇关于如何使用scss同时使用媒体查询和选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!