是否可以将'经典”CSS 规则与包含相同样式的媒体查询合并?
P粉129168206
P粉129168206 2024-02-03 19:13:56
0
2
426

我想知道是否可以组合应用于同一元素并包含相同样式的 2 个规则,但其中一个规则位于媒体查询中并得到类似于以下内容的内容:

.a,
.b .a {
  color: white;
  background-color: black;
}

规则是:

  • 根据 prefers-color-scheme 将颜色应用于 .content
  • inputchecked 时,更改 .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 将获得黑色背景和白色。

这两个规则应用相同的样式。

有没有办法结合这些规则?

P粉129168206
P粉129168206

全部回复(2)
P粉163951336

雷雷 雷雷
P粉543344381

你无法使用原生 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});
  }
}

最后,您可以使用它来创建尽可能多的主题,只需更改变量即可:

@include themed-style(dark);
@include themed-style(light);

如果您想查看与原始代码相同的输出,可以此处尝试

复制粘贴完整代码以查看转换:

: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);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!