CSS相同的类名使用相同的样式

3

HTML:

<div id="wrapper">
  <div class="body">
     text text text
  </div>
  <div class="comment_submit">
       <!-- here goes username text field !-->
       <div class="body">
         <textarea></textarea>
       </div>
       <!-- here goes submit button !-->
    </div>
</div>

CSS:

#wrapper{
  float:left;
  width:100%;
}
#wrapper .body{
  border:1px solid red;
  background:#f5f5f5;
  padding:5px;
}
.comment_submit .body{
  border:2px solid red;
  background:#cccccc;
}

为什么位于comment_submit div内部的body div会获得#wrapper .body样式,而不仅仅是.comment_submit .body样式?

我知道#wrapper .body样式包括所有位于#wrapper内部的.body div,但我该如何停止这种情况发生?

3个回答

3
这是您的问题的解决方案:
#wrapper > .body{
  border:1px solid red;
  background:#f5f5f5;
  padding:5px;
}
  1. #wrapper .body = "选择每一个是#wrapper的后代的.body元素".
  2. .comment_submit .body = "选择每一个是.comment_submit的后代的.body类元素".

ID选择器比类选择器具有更高的优先级,因此第一个选择器中定义的属性优先于第二个选择器中的属性。

  • 该解决方案利用了子选择器>,它表示:“选择每个是#wrapper直接子元素的.body元素。

1

#wrapper .body{} 将应用于所有 .body 类,只要它们仍在 #wrapper 内部,无论它们有多深。

我建议将位于 .comment_submit 内部的 .body 重命名为 .comment_submit_body 以解决您的问题。

您的类名不应该对应不同的样式。


0

这与选择器的特异性有关。简而言之,这意味着#id选择器(第一种情况)优先于class选择器(第二种情况)。您可以通过以下方式进行修复:

#wrapper .comment_submit .body{
  border:2px solid red;
  background:#cccccc;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接