`#parent span`风格覆盖了`.child span`风格

时间:2013-10-07 00:03:12

标签: html css

我的情况是.menu中有#header,当我通过.menu之类的css选择器访问.menu a个孩子时,它正在使用而是#header a

我希望.menu a覆盖#header a,因为它更接近a元素。为什么不发生这种情况?我假设它与基于以下示例的id相比是一个类。

在示例中,是否有一种好方法可以在#red span内覆盖.blue span css,而不会限制父样式?

以“好的方式”我想我的意思是灵活的。例如,.blue可以是由许多地方使用的php框架创建的元素(可能不在id样式的父元素中,或者可能在不同id上设置的父类中)。

这是example。除#green之外的所有内容仍为红色:

HTML:

<div id="red">
    <span>red</span>
    <div class="blue">
        <span>blue(class) - should be blue</span>
    </div>
    <div id="green">
        <span>green(id) - should be green</span>
    </div>
    <div class="green">
        <span>green(class) - should be green</span>
    </div>
    <div>
        <span>no child div style - should still be red</span>
    </div>
</div>

CSS:

#red span {
    color: red;
}
.blue span {
    color: blue;
}
.green, #green span {
    color: green;
}

4 个答案:

答案 0 :(得分:2)

应用CSS规则(不含!important)的优先级是:

  1. 选择器中的ID数量。如果画画,
  2. 属性和类的数量。如果画画,
  3. 名称或伪元素。如果画画,
  4. CSS文件的最后一个声明。当然,这绝不会吸引人。
  5. 由于#red span有ID,而.green没有,#red span适用。

    有关首先应用哪个CSS规则的进一步说明,请查看此nice article on smashing magazine

    要解决此问题,您可以use a more specific rule。通过这种方式,它获得了第一名,但由于它有额外的类,因此你的规则因第二名而获胜。

答案 1 :(得分:1)

选择器特异性表明id优先于类。尽管蓝色级别在级联中处于红色之后,但由于特异性,红色优先。如果需要,您可以使用选择器#red .blue span

答案 2 :(得分:1)

最简单,最干净:

http://jsfiddle.net/f4ke2/7/

#red {
    color: red;
}
.blue span {
    color: blue;
}
.green, #green span {
    color: green;
}

或者如果你这样做怎么办? :)

#red > span {
    color: red;
}

OR

 #red .blue span {color: blue;}

OR

.blue span {
    color: blue !important;
}

OR表示“灵活性”

#red .blue span, .blue span, #someotherID .blue span {color: blue;}

或者像这个可怕的东西

var id = $("#red");
id.addClass(id.attr("id")).removeAttr("id");

答案 3 :(得分:0)

如果您正在使用样式表(在框架中或其他方式)按类分配属性,即使用类选择器,则只需在编写其他CSS规则时将此考虑在内。所以这是一个规范编码(HTML和CSS)的问题,而不是使用一些技巧来摆脱正常的CSS原则。

基本上,仅在您希望受影响的元素上设置属性,而不使用覆盖范围太广的选择器。比如,如果你想将一些元素中的文本设置为红色,只在该元素上设置color: red,而不是在其后代上,除非你真的想要覆盖它们可能具有的任何设置。

例如,如果有一个带有.foo { color: blue }的样式表,那么这将影响类foo中的任何元素,除非被其他规则覆盖,如CSS级联。因此,如果您不希望在<div id=xxx>...<span class=foo>...</span>...</div>之类的情况下覆盖它,则无法设置#xxx span { color: red },因为您可以通过更具体的选择器覆盖规则。在这个意义上使用#xxx { color: red }是安全的,因为span(有颜色集)不会继承其父颜色。

!important中使用.foo { color: blue !important }似乎可以解决问题,但!important使样式表难以管理和维护。当你需要一个工具来覆盖特异性效果时它也会产生问题但是却不能,因为你已经解雇了这个武器。规则.foo { color: blue !important }#xxx span { color: red !important }无效。

相关问题