1. 两个选择器的异同:
伪类选择器是用来向某些选择器来添加效果。不修改DOM内容,通过一些特定的选择器根据特定的状态、特定条件来修改元素的杨氏。比如:悬停(hover
)、点击(active
)以及文档中不能通过其它选择器选择的元素(这些元素没有 ID 或 class 属性),例如第一个子元素(first-child
)或者最后一个子元素(last-child
)。
伪元素选择器是一个附加在选择器末尾的关键词,通过伪元素您不需要借助元素的 ID 或 class 属性就可以对被选择元素的特定部分定义样式。例如通过伪元素您可以设置段落中第一个字母的样式(::first-letter
),或者在元素之前(::before
)、之后插入一些内容(::after
)等等。伪元素可能改变DOM结构,创造了虚拟的DOM。
2. 常见伪元素选择器:
::after
::before
::first-letter
::first-line
::selection
::placeholder
3. 常见伪类选择器:
(1)结构伪类选择器:
:first-child
:last-child
:nth-child(n)
:nth-last-child(n)
:first-of-type
:last-of-type
:nth-of-type(n)
:nth-last-of-type(n)
:only-child
:only-of-type
:root
:empty
(2)反选伪类选择器:
父元素 (空格) :not(标签名)
(3)目标伪类选择器:
:target
(4)UI元素状态选择器:
:enabled
:disabled
:checked
(5)动态伪类选择器:
:link
:visited
:hover
:active
(6)用户行为伪类选择器
:focus