首页 > 解决方案 > 如何根据 div 的类对 div 中的元素进行样式设置?

问题描述

基本上,我正在为我的网站创建一个深色主题系统,并在dark调用适当的函数时将类添加到 html 标记中。我正在使用 CSS 变量--light-theme-bg: white;,并使用var(--light-theme-bg);. 如何hr根据dark该类是否附加到html元素来设置特定元素的样式。我怎样才能做到这一点?

标签: htmlcssthemesstyling

解决方案


范围界定是你的朋友。您需要在 CSS 中添加两条规则。一种用于深色主题,一种用于浅色主题。

在这些规则中,您可以定义一个--backgroundvar。

所有引用该 var 的子元素都会尊重它。

.light {
  --background: #f9f9f9;
}

.dark {
  --background: #191919;
}

.first,
.second {
  color: red;
  background: var(--background);
}
<div class="light">
  <div class="first"> I'm the first div</div>
  <div class="second">I'm the second div</div>
</div>

<div class="dark">
  <div class="first"> I'm the first div</div>
  <div class="second">I'm the second div</div>
</div>


推荐阅读