我正在尝试根据它们的祖先(特别是不是父母)对一些按钮进行主题化,所以...我有以下 HTML 结构
<body class="theme-a">
<section class="container">
<form class="theme-b">
<div class="button-group">
<button type="button">Button B1</button>
<button type="button">Button B2</button>
</div>
<div class="button-group">
<button type="button">Button B3</button>
<button type="button">Button B4</button>
</div>
</form>
<form>
<div class="button-group">
<button type="button">Button A1</button>
<button type="button">Button A2</button>
</div>
<div class="button-group">
<button type="button">Button A3</button>
<button type="button">Button A4</button>
</div>
</form>
</section>
</body>
嗯,如您所见,有两个主题
.theme-a
和 .theme-b
CSS 代码,如下所示:
.theme-a {
background: #999;
}
.theme-b {
background: #555;
}
.theme-a button {
background: #222;
}
.theme-b button {
background: #69C;
}
问题是:如果您切换主题类(A 与 B,B 与 A),您会注意到 A 主题上的按钮(与主题类有更近的祖先,保留了远祖先的样式,蓝色背景而不是黑色背景)。
如何根据最接近的祖先设置按钮属性来实现适当的特异性?
这是 JSfiddle 的链接:http://jsfiddle.net/XVaQT/1/
我希望我能清楚地解释:)
谢谢
幸运的是,使用CSS,您可以组合多个选择器来为许多元素指定相同的样式,我用一个工作示例更新了您的jsfiddle,只需更改类
theme-a
和theme-b
,正如您在问题中所说,看看它工作:http://jsfiddle.net/cchana/XVaQT/3/
我所做的就是添加第二个选择器,您只是在其中寻找
button
,它是具有 theme-a
类的元素的后代:
.theme-a button {
background: #222;
}
它现在还会查找
button
,它是具有类 theme-b
的元素的后代,而该类本身又是具有类 theme-a
的元素的后代:
.theme-a button,
.theme-a .theme-b button {
background: #222;
}
无需向
!important
值添加 background
,因为由于此选择器更加具体,它将覆盖为 .theme-b button
定义的样式。
这是使用
:has
的 2023 年解决方案,该解决方案基于最近祖先上的 .theme-*
类设置按钮样式,并允许在祖先上无限嵌套 .theme-*
类。
.theme-a:not(:has([class*='theme-'])) button {
/* theme-a button styles */
}
选择器说:“给我所有
.theme-a
元素,但不要包含嵌套 theme-*
的元素。” (具体来说,不是具有包含 theme-
的类属性的子元素。)