CSS中#testid.testclass与#testid .testclass的区别
在一些面试中常常会考到一些很奇怪但又比较基础的问题,就如本文所要讲述的css选择器使用上的一个细节。 如下css和html代码,你能说出哪块是啥颜色吗?(如果你看一眼就知道了,那么请随意~) <sty... |
在一些面试中常常会考到一些很奇怪但又比较基础的问题,就如本文所要讲述的css选择器使用上的一个细节。
如下css和html代码,你能说出哪块是啥颜色吗?(如果你看一眼就知道了,那么请随意~)
<style> #testid.testclass{ background: red; } #testid .testclass{ background: green; } </style>
<div id="testid" class="testclass" style="width:200px;height:200px;margin:0;"> <div class="testclass" style="width: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"
.
(转发请注明转自:学PHP)
- 『精品素材』15套极好的高质量免费纹理 (2013-05-24 23:48:13)
- javascript实现继承的方式 (2013-05-24 23:48:13)
- cookie 和session 的区别详解 (2013-05-24 23:48:14)
- JavaScript完美验证URL正则 (2013-05-28 12:54:26)
- css3新属性text-shadow (2013-06-11 20:48:14)
- IE下CSS问题及解决 (2013-05-24 23:48:13)
- 一款响应式的(电子报)Newsletter 模板 – Antwort (2013-05-24 23:48:13)
- 移动平台前端开发总结(针对iphone,Android等手机) (2013-05-24 23:48:13)
- 驴途网-技术小结1 (2013-05-24 23:48:12)
- HTML5 经量级框架 jQuery Mobile (Button,Icon,分组功能button,具有内联样式的button) - 7.4 (2013-05-24 12:48:15)