伪元素与伪类的区别

伪类和伪元素的异同

  1. 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.

  2. CSS Selectors Level 3
    该规范中为伪类和伪元素做了区分,伪类使用单冒号,伪元素开始使用双冒号。
    比如
    伪类:first-child
    伪元素::first-line、::first-letter、::before、::after
    CSS 3在CSS2.1的基础上增加了不少伪类:target、UI元素状态的伪类:checked等、结构性伪类:nth-child()等,具体可以看规范。

  3. CSS Selectors Level 4草案
    该草案中又增加了很多新的伪类,比如与input控制状态、值状态、值校验相关的伪类,树形结构的伪类,网格结构的伪类等。

  4. 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。

  5. 常见应用
    伪类:

  1. a链接样式
  2. 隔行变色
    伪元素:
  3. 最常见的使用伪元素after清除浮动,
    .fix{*zoom:1;}
    .fix:after,.fix::after{display: block; content: “clear”; height: 0; clear: both; overflow: hidden; visibility: hidden;}
  4. letter-spacing+first-letter实现按钮文字隐藏
  5. 首行、首字母样式

总结
伪元素和伪类之所以这么容易混淆,是因为他们的效果类似而且写法相仿,但实际上 css3 为了区分两者,已经明确规定了伪类用一个冒号来表示,而伪元素则用两个冒号来表示。

猜你喜欢

转载自blog.csdn.net/weixin_52630329/article/details/111712986