【问题标题】:How to inherit from ancestor and not parent in CSS?如何在 CSS 中继承祖先而不是父级?
【发布时间】:2016-03-23 14:43:23
【问题描述】:

这是我的代码:

.ancestor { 
    background-color: #ccc;
}

.parent { 
    background-color: #fff;
}

.child {
    /* ??? */
}

我怎样才能让.child继承background-color: #ccc;而不更改类声明顺序?

我尝试了background-color: inherit;,但我得到的只是background-color 属性的完全重置(即没有颜色)。

还请注意,.ancestor.parent 都不能更改。

【问题讨论】:

  • 有几种方法可以做到这一点,具体取决于 HTML(您应该将其添加到您的问题中)。例如,给祖先和孩子同一个类,并在该类选择器中设置颜色。

标签: css twitter-bootstrap plugins themes


【解决方案1】:

你可以这样做:

.ancestor { 
    background-color: #ccc;
}

.parent { 
    background-color: #fff;
}

.child {
    background-color: #ccc;
}

或者你可以这样做:

.ancestor { 
    background-color: #ccc;
}

.parent { 
    background-color: #fff;
}

.child {
    /* ??? */
}

并且拥有

html div 或类似的东西:

<div class="ancestor child"></div>

【讨论】:

  • 当然,但是.ancestor 的值来自一个主题。如果主题发生变化,则会破坏页面外观。
  • OP 明确指出“我怎样才能拥有.child inherit background-color”
  • @Billy 是的,抱歉修复了它
  • 我已更新我的帖子以更好地反映我的问题。
【解决方案2】:

这样就可以了:

.ancestor, .child { 
    background-color: #ccc;
}

.parent { 
    background-color: #fff;
}

你可以这样做,

.ancestor { 
    background-color: #ccc;
}

.parent { 
    background-color: #fff;
}

.child {
    background-color: #ccc;
}

【讨论】:

  • ancestor 类由主题定义。如果主题发生变化,则会破坏页面外观。
  • 如果你想格式化你的child 就像你的ancestor 一样,你能不能把ancestor 类添加到你的子标签中?
  • @Dandorid:你如何在 CSS 中做到这一点?
  • 如果您的.ancestor 定义中只有颜色定义,您可以只写&lt;htmltag class='child ancestor'&gt;,它将祖先的颜色定义添加到&lt;htmltag&gt;。您省略了子项中的颜色定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 2016-05-08
  • 1970-01-01
  • 2011-06-21
  • 2011-06-07
  • 1970-01-01
相关资源
最近更新 更多