伪类和伪元素的异同
-
W3C CSS 2.1 Selectors
对伪类和伪元素没有做出区分,都是使用一个冒号
比如
伪类:first-child,
伪元素:first-line
PS:在该规范中明确提到了a链接的几种伪类的书写顺序:
Note that the A:hover must be placed after the A:link and A:visited rules, since otherwise the cascading rules will hide the ‘color’ property of the A:hover rule. Similarly, because A:active is placed after A:hover, the active color (lime) will apply when the user both activates and hovers over the A element. -
CSS Selectors Level 3
该规范中为伪类和伪元素做了区分,伪类使用单冒号,伪元素开始使用双冒号。
比如
伪类:first-child
伪元素::first-line、::first-letter、::before、::after
CSS 3在CSS2.1的基础上增加了不少伪类:target、UI元素状态的伪类:checked等、结构性伪类:nth-child()等,具体可以看规范。 -
CSS Selectors Level 4草案
该草案中又增加了很多新的伪类,比如与input控制状态、值状态、值校验相关的伪类,树形结构的伪类,网格结构的伪类等。 -
CSS Pseudo-Elements Module Level 4——W3C First Public Working Draft, 15 January 2015
增加了一些伪元素,如:
Selecting Highlighted Content: the ::selection, ::spelling-error, and ::grammar-error pseudo-elements,
Placeholder Input: the ::placeholder pseudo-element。 -
常见应用
伪类:
- a链接样式
- 隔行变色
伪元素: - 最常见的使用伪元素after清除浮动,
.fix{*zoom:1;}
.fix:after,.fix::after{display: block; content: “clear”; height: 0; clear: both; overflow: hidden; visibility: hidden;} - letter-spacing+first-letter实现按钮文字隐藏
- 首行、首字母样式
总结:
伪元素和伪类之所以这么容易混淆,是因为他们的效果类似而且写法相仿,但实际上 css3 为了区分两者,已经明确规定了伪类用一个冒号来表示,而伪元素则用两个冒号来表示。