目标是让元素的父级决定它的样式。所以.dark .light p
会有浅色文本、.dark p
深色文本和.light .dark .light p
浅色文本。
该p
元素甚至可能不是直接子元素,.dark
因此.light
会有.light .dark div.wrap div.inner p
深色文本。
由于 CSS 的级联特性,它似乎更喜欢最后一条规则。这甚至可能吗?
/* Doesn't work - switching the order isn't helpful
as the opposite problem occurs */
.dark p {
color: #000;
}
.light p {
color: #aaa;
}
/* Works, but in my use case I need to specify attributes on
specific element. */
/*
.dark {
color: #000;
}
.light {
color: #aaa;
}
*/
/* Works but not realistic if paragraph is nested deeper */
/*
.dark > p {
color: #000;
}
.light > p {
color: #aaa;
}
*/
/* Only works on the first two levels */
/*
.dark p {
color: #000;
}
.light p {
color: #aaa;
}
.dark .light p {
color: #aaa;
}
.light .dark p {
color: #000;
}
*/
<div class="light">
<p>Light text</p>
<div class="dark">
<p>Dark text</p>
<div class="light">
<p>Light text</p>
</div>
</div>
</div>
<div class="dark">
<p>Dark text</p>
<div class="light">
<p>Light text</p>
<div class="dark">
<p>Dark text</p>
</div>
</div>
</div>