常用的几种写法:
一.按所有兄弟元素计算
- 所有兄弟中的第一个
:first-child
- 所有兄弟中的最后一个
:last-child
- 所有兄弟中的第n个
: nth-child(n)
举例:
/* 选中的是div的第一个儿子p元素(按照所有兄弟元素计算) */
div>p:first-child {
color: blue;
}
/* 选中的是div的最后一个儿子p元素(按照所有兄弟元素计算) */
div>p:last-child {
color: blue;
}
/* 选中的是div的第n个儿子p元素(按照所有兄弟元素计算) */
div>p:nth-child(3) {
color: blue;
}
/* 选中的是div的偶数个儿子p元素(按照所有兄弟元素计算) */
div>p:nth-child(2n) {
color: blue;
}
二.按同类型的兄弟元素计算
- 所有同类型兄弟中的第一个
:first-of-type
- 所有同类型兄弟中的最后一个
:last-of-type
- 所有同类型兄弟中的第n个
:nth-of-type(n)
举例:
/* 选中的是div的第一个儿子p元素(按照所有同类型兄弟元素计算) */
div>p:first-of-type {
color: blue;
}
/* 选中的是div的最后一个儿子p元素(按照所有同类型兄弟元素计算) */
div>p:last-of-type {
color: blue;
}
/* 选中的是div的第n个儿子p元素(按照所有同类型兄弟元素计算) */
div>p:nth-of-type(5) {
color: blue;
}
注意:
关于括号内n的写法:
- 0或不写:什么都不选
- n:选中所有子元素
- 正整数:选中对应序号的子元素
- 用公式,但必须是 an+b 的形式
如:选中序号为偶数的子元素:2n(或 even)
选中序号为奇数的子元素:2n+1(或 odd) - -n+5:前五个数
举例:
/* 选中的是div的偶数个儿子p元素(按照所有兄弟元素计算) */
div>p:nth-child(2n) {
color: blue;
}
了解就行的写法:
- 所有兄弟元素中的倒数第n个
:nth-last-child(n)
- 所有同类型兄弟元素中的倒数第n个
:nth-last-of-type(3)
- 没有兄弟的元素
:only-child
- 没有同类型兄弟的元素
:only-of-type
- 根元素
:root
- 没有内容的元素
:empty
注意:空格也是内容
举例:
/* 选中的是div的倒数第n个儿子p元素(按照所有兄弟元素计算) */
div>p:nth-last-child(3) {
color: blue;
}
/* 选中的是div的倒数第n个儿子p元素(按照所有同类型兄弟元素计算) */
div>p:nth-last-of-type(3) {
color: blue;
}
/* 选中的是没有兄弟的span元素 */
span:only-child {
color: blue;
}
/* 选中的是没有同类型兄弟的span元素 */
span:only-of-type {
color: blue;
}
/* 选中的是根元素 */
:root {
background-color: gray;
}
/* 选中的是没有内容的div元素 */
div:empty {
width: 40px;
height: 40px;
background-color: blue;
}