在一些面试中常常会考到一些很奇怪但又比较基础的问题,就如本文所要讲述的css选择器使用上的一个细节。
如下css和html代码,你能说出哪块是啥颜色吗?(如果你看一眼就知道了,那么请随意~)
<style> #testid.testclass{ background: red; } #testid .testclass{ background: green; } </style>
<div id="testid" class="testclass" style="200px;height:200px;margin:0;"> <div class="testclass" style="100px;height:100px;margin:10px auto"> 内 </div>外 </div>
口说无凭,咱们程序员都是以实际测试为主,如下显示效果(其他html无关代码略)
对于#testid.testclass与#testid .testclass的区别,在我学习css的道路上并未遇到过,可能是因为我学的乱吧,但回头看看,自己琢磨下也是可以找到啥区别的,只是缺乏官方的解释(这个解释有空我去找找<偷懒了>,已经补充部分,见本文补充<文章末尾>)。
时间不多了,下面直接说下我的理解吧。
首先#testid.testclass,在id后紧跟点号和class的写法,那么表示是匹配id为testid的元素中再匹配class是testclass的元素。
最后#testid .testclass,在id后加空格然后跟上点号和class的写法,那表示匹配id为testid的元素,然后再在该元素的子孙元素中匹配class是testclass的元素。
PS:上面的#testid可以是其他如div标签、class(class前面要加点号哦,这个可是比较特殊的),其他变种的情况大家自己琢磨吧!!!
PPS:最后我还联想到,除了#testid .testclass中的空格所代表的子孙关系,还有~表示的兄弟关系、+表示的相邻兄弟关系、>表示的子元素关系。
补充:关于官方文档对这方面的一些说明(摘自:http://www.w3.org/TR/2011/REC-css3-selectors-20110929/)
Pattern | Meaning | Described | First defined in CSS level |
E F | an F element descendant of an E element | Descendant combinator | 1 |
E > F | an F element child of an E element | Child combinator | 2 |
E + F | an F element immediately preceded by an E element | Adjacent sibling combinator | 2 |
E ~ F | an F element preceded by an E element | General sibling combinator | 3 |
类选择器的使用:
CSS examples:
We can assign style information to all elements with class~="pastoral"
as follows:
*.pastoral { color: green } /* all elements with class~=pastoral */
or just
.pastoral { color: green } /* all elements with class~=pastoral */
The following assigns style only to H1 elements with class~="pastoral"
:
H1.pastoral { color: green } /* H1 elements with class~=pastoral */
Given these rules, the first H1
instance below would not have green text, while the second would:
<H1>Not green</H1> <H1 class="pastoral">Very green</H1>
The following rule matches any P
element whose class
attribute has been assigned a list of whitespace-separated values that includes both pastoral
and marine
:
p.pastoral.marine { color: green }
This rule matches when class="pastoral blue aqua marine"
but does not match for class="pastoral blue"
.