【问题标题】:CSS specificity and/or inheritance with ancestorsCSS 特异性和/或与祖先的继承
【发布时间】:2012-11-15 14:49:46
【问题描述】:

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

希望我解释清楚:)

谢谢 ​

【问题讨论】:

  • 特异性的问题在于它没有最近或最远的祖先或兄弟姐妹的概念。即使组合器在特异性上也没有区别。 E F 同样特定于 E &gt; F
  • @BoltClock 直系后代规则不在讨论之列 :) 正如我所说,问题与祖先有关,而不仅仅是与父母有关

标签: css inheritance css-specificity


【解决方案1】:

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

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

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

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

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

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

【讨论】:

  • 如果我有 3 或 4 个主题嵌套怎么办(实际上,我正在处理 4 个主题的事情)?想象一下body 的主题,section 的主题和该部分的header 的主题。我必须写出所有主题组合?一点都不好!
  • 我同意它会变得一团糟,但不幸的是,CSS 只能用一种方式!您可以选择父母的孩子,但不能选择孩子的父母。为了便于维护,LESS 可能是一个不错的选择,它允许您嵌套/重用样式。
  • 我知道您不能针对孩子的父母。我也在为我的样式使用 Sass/SCSS,但我正在努力为这个问题找到一个优雅的解决方案,希望 :)
猜你喜欢
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 2012-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
相关资源
最近更新 更多