定义
伪类选择器
什么是伪类?
伪类是选择器,用于选择处于特定状态的元素
:伪类名
The pseudo-class concept is introduced to permit selection based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors.
翻译过来
伪类存在的意义是为了 通过选择器,格式化DOM树以外的信息以及不能被常规CSS选择器获取到的信息。
即伪类的功能有两种:
1.格式化DOM树以外的信息。比如: a> 标签的 :link :visited 等。这些信息不存在于DOM树中。
“文档对象模型”(Document Object Model)
2.不能被常规CSS选择器获取到的信息。比如:要获取第一个子元素,我们无法用常规的CSS选择器获取,但可以通过 :first-child 来获取到。
伪类其实是弥补了CSS选择器的不足,用来更方便地获取信息。
伪元素
Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element’s content. Pseudo-elements allow authors to refer to this otherwise inaccessible information. Pseudo-elements may also provide authors a way to refer to content that does not exist in the source document (e.g., the ::before and ::after pseudo-elements give access to generated content).
即 伪元素可以创建一些文档语言无法创建的虚拟元素。
比如:文档语言没有一种机制可以描述元素内容的第一个字母或第一行,但伪元素可以做到(::first-letter、::first-line)。同时,伪元素还可以创建源文档不存在的内容,比如使用 ::before 或 ::after。
伪类
-
first-child
选择第一个子元素
first-of-type
选择元素中指定类型 -
last-child
last-of-type -
nth-child()
选中指定第几个的子元素
()中可填变量
2n:偶数 == even
2n+1:奇数行 == oddnth-of-type()选中第几个某类型元素
实现 倍数、 隔行变色
- :only-child 匹配没有兄弟姐妹的孤儿元素。
- :link 匹配未访问的链接。
- :visited 匹配访问后的链接。
- :hover 当用户将鼠标悬停在元素上时匹配。
伪元素
- ::first-line 首行元素
- ::first-letter 首字母
- ::selection 用户选中的部分
使用:: before和:: after生成内容
与content属性一起使用以使用CSS将内容插入文档中。
在被选元素之后插入内容。需要指定content属性来插入内容。
.clear::after {
content: '';
display: block;
clear: both;
}
每次需要清除浮动的时候加class:".clear"
相当于在元素最后加入空白快 且具有clear:both属性