前言
伪类与伪元素的问题总是容易弄混淆,本文在此进行总结,希望对你有帮助
伪类和伪元素的概念
A pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer. They tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup, and giving you more flexible, maintainable code.
伪类是一种选择处于特定状态的选择器,其作用就是在文档的某部分添加了一个类,为我们提供更灵活、可维护的代码。
Pseudo-elements behave in a similar way, however they act as if you had added a whole new HTML element into the markup, rather than applying a class to existing elements.
伪元素与伪类类似,区别在于伪元素就像添加了一个DOM节点到DOM树中,而不是将类添加到现有元素。
伪类的分类
伪元素的分类
伪类与伪元素的写法
Pseudo-classes are keywords that start with a colon:
Pseudo-elements start with a double colon ::
CSS3明确规定了,伪类用一个冒号(:)来表示,而伪元素则用双冒号(::)来表示
伪类与伪元素的异同
相同点
- 伪类与伪元素都用于向选择器加特殊效果的。
- 伪类和伪元素都用于表示文档树以外的"元素"。
不同点
- 可以同时使用多个伪类,而只能同时使用一个伪元素。
- 伪元素创建了DOM树之外的元素,而伪类没有。
- 伪类能选择具体的文档树元素。但伪元素选择的不是具体的文档树元素,更多的是一个独立于文档树的“抽象元素”。
参考