4

我正在尝试根据他们的祖先(不是父母,特别是)来设置一些按钮的主题,所以......我有以下 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/

我希望我解释清楚:)

谢谢​</p>

4

1 回答 1

1

值得庆幸的是,使用 CSS,您可以组合多个选择器来为许多元素指定相同的样式,我用一个工作示例更新了您的 jsfiddle,只需更改类theme-a,并且theme-b正如您在问题中所说,看到它工作:http:// jsfiddle.net/cchana/XVaQT/3/

我所做的只是添加第二个选择器,您只是在寻找一个button具有类的元素的后代theme-a

.theme-a button {
    background: #222;
}

它现在还查找 abutton是具有类的元素的后代,该类theme-b本身是具有类的元素的后代theme-a

.theme-a button,
.theme-a .theme-b button {
    background: #222;
}

不需要在!important您的值中添加 a,因为由于此选择器更具体background,它将覆盖定义的样式。.theme-b button

于 2012-11-15T15:57:02.827 回答