CSS Cascade HELP - 需要子级覆盖父级

时间:2013-06-27 19:08:50

标签: css css-selectors

我正在定义颜色块...

.custom1 {
    background: red;
}
.custom1 h3 {
    color: white;
}
.custom2 {
    background: blue;
}
.custom2 h3 {
    color: #0f0;
}
.custom3 {
    background: #000;
}
.custom3 h3 {
    color: #f0f;
}

够容易

当我的积木相互嵌套时,我的问题就出现了。

H3的最顶级父包装器声明会覆盖H3的子包装器声明(这对我来说似乎不正确)

这是我的问题的一个小问题

http://jsfiddle.net/ujrLf/

添加大于号“>”确实解决了问题,但只针对第一级。

如何强制子元素声明覆盖父元素?

4 个答案:

答案 0 :(得分:2)

感谢所有尝试过的人。这是我要解决的问题......

这是小提琴! http://jsfiddle.net/4wAtz/1/

.custom1 {
    background: red;
}
.custom1 h3, 
[class*='custom'] .custom1 h3,
[class*='custom'] [class*='custom'] .custom1 h3,
.and-so-on, .and-so-on, .and-you-get-it
{
    color: white;
}
.custom2 {
    background: blue;
}
.custom2 h3, 
[class*='custom'] .custom2 h3,
[class*='custom'] [class*='custom'] .custom2 h3
{
    color: #0f0;
}
.custom3 {
    background: #000;
}
.custom3 h3, 
[class*='custom'] .custom3 h3,
[class*='custom'] [class*='custom'] .custom3 h3
{
    color: #f0f;
}

它没有我想要的那么优雅,但它有效!我只需要推断出我能看到的那么多级别(加1)。

答案 1 :(得分:0)

使用>似乎也解决了这个问题,即使是在更低的水平上。见this fiddle

.custom1 > h3 {
    color: white;
}
.custom2 > h3 {
    color: #0f0;
}
.custom3 > h3 {
    color: #f0f;
}

您还可以在要覆盖所有其他CSS命令的行上使用!important 使用HESITANTLY,查看评论,或者您可以进一步提高特异性

答案 2 :(得分:0)

当存在具有相同特定级别的样式时,它们将按读入顺序使用。这就是为什么当你有一个“.custom3”包装器时,因为它是在样式列表中读取的最后一个,“。 custom3 h3“颜色胜过”.custom1 h3“和”.custom2 h3“颜色。

您可以获得的具体内容越多,这些样式的优先级就越高。例如,“。custom3 h3”将比“h3”具有更高的优先级。并且“#content .custom3 h3”将具有更高的优先级。

答案 3 :(得分:0)

为什么你需要给h3颜色。您可以轻松地为.custom1类提供相同的颜色,最终将其应用于其所有子项。

为什么不将CSS改为这样的?

h3 {
    margin: 0;
    text-align: center;
}
[class*='custom'] {
    padding: 5px;
}
.custom1 {
    background: red;
    color: white;
}
.custom2 {
    background: blue;
    color: #0f0;
}
.custom3 {
    background: #000;
      color: #f0f;
}

检查新的小提琴http://jsfiddle.net/ujrLf/4/