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,但我该如何阻止它呢?
最佳答案
这解决了您的问题:
#wrapper > .body{
border:1px solid red;
background:#f5f5f5;
padding:5px;
}
#wrapper .body
= "选择每个.body
是#wrapper
的后代。.comment_submit .body
= "选择每个body
类,它是.comment_submit
的后代。
ID 选择器比类选择器具有更高的特异性,因此第一个选择器中定义的属性优先于 #2 中的属性。
- 该解决方案利用子选择器
>
,它表示:“选择每个.body
元素,它是的直接子元素>#wrapper
.
关于html - css 相同的类名获得相同的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9021430/