伪类选择器
- 选择第一个元素,以下表示选择第一个p元素
p:first-child{
color: red;
}
- 选择最后一个元素,以下表示选择最后一个p元素
p:last-child{
color: red;
}
- 选择第几个元素,以下表示选择第2个p元素
p:nth-child(2){
color: red;
}
- 选择奇数项的元素(注:所选元素为兄弟关系且为同一元素)
p:nth-child(odd){
color: red;
}
另一种写法
p:nth-child(2n+1){
color: red;
}
- 选择偶数项的元素(注:所选元素为兄弟关系且为同一元素)
p:nth-child(even){
color: red;
}
另一种写法
p:nth-child(2n){
color: red;
}
- 选中第n个以后的元素(注:所选元素为兄弟关系),以下表示选中第五个以后的元素
p:nth-child(n+5){
color: red;
}
- 选中第n个以前的元素(注:所选元素为兄弟关系),以下表示选中第五个以前的元素
p:nth-child(-n+5){
color: red;
}
- 选中指定标签的第n个,以下表示选中p元素中的第五个
p:nth-of-type(5){
color: red;
}
- 选中除了指定标签的第n个,改变其他兄弟元素,以下表示p元素中除了第五个改变其他p元素
p:not(:nth-of-type(5)){
color: red;
}
- 选中除了指定标签的第n个和第n个外,改变其他兄弟元素,以下表示p元素中除了第五个和第八个改变其他p元素
p:not(:nth-of-type(5)):not(:nth-of-type(8)){
color: red;
}
- 选中除了指定标签的第n个到第n个之间,改变其样式,以下表示选中第二个p到第五个p之间的元素
p:nth-child(2):nth-child(5){
color: red;
}
动态伪类选择器
link:未访问状态
hover:鼠标悬停
active:鼠标点击时
visited:已访问
focus:用于选取获得焦点的元素
书写格式:
a:link {color: red;}
a:visited { color: red;}
a:hover {color: red;}
a:active {color: red;}
input:focus {border-color: red;}
- 选中第一个指定类型的标签,选中第一个a
a:first-of-type { color: red;}
- 选中最后一个指定类型的标签,选中最后一个a
a:last-of-type { color: red;}
- 选中无兄弟元素的标签,以下表示选中无兄弟元素的a
a:only-child {color: red; }
- 选中没有元素内容的标签,以下表示选中无元素内容的a (注:空格与回车也算元素内容)
a:empty {
display: inline-block;
width: 100px;
height: 100px; }
- 选中元素内容的第一行/首字母及汉字添加样式
p::first-letter {color: red;}
p::first-line {color: red;}
- 选中元素内容的前提下,改变其选中后的样式(注:只能设置文本颜色和背景色且在鼠标将内容选中的情况下)
p::selection {
color: red;
background-color: yellow;
}