我正在尝试根据他们的祖先(特别是 parent )为一些按钮设置主题,所以......我有以下 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
类元素的后代,它本身是 类元素的后代>主题-a
:
.theme-a button,
.theme-a .theme-b button {
background: #222;
}
不需要将 !important
添加到您的 background
值,因为它将覆盖为 .theme-b 按钮定义的样式
感谢这个选择器更具体。
关于CSS 特异性和/或与祖先的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13399968/