CSS3:nth-child使用方法

CSS3:nth-child选择属于其父元素的指定位置的子元素。写法上大体有以下几种:

1、简单数字
获取具体单个元素

ul li:nth-child(3) {background-color: #000;} //设置第3个li的背景色为黑色
  • 1

2、公式写法
具体格式:nth-child(an+b),a与b为任意有效的整数,n取值范围是有些的自然数,最终计算相应结果,b可以省略。

ul li:nth-child(3n) {background-color: #000;}  //设置第3,6,9,...等有效li的背景色为黑色

ul li:nth-child(3n+1) {background-color: #000;}  //设置第1,4,7,...等有效li的背景色为黑色 

ul li:nth-child(-3n) {background-color: #000;}  //计算结果均为负,没有选中任何li

ul li:nth-child(-3n+5) {background-color: #000;}  //设置第2,5个li的背景色为黑色
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3、奇偶选择
:nth-child(odd) 匹配序号为奇数的元素,等同于:nth-child(2n+1)
:nth-child(even)匹配序号为偶数的元素,等同于:nth-child(2n)

--------------------- 本文来自 庭域 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/Wong_Lin/article/details/52796866?utm_source=copy

发布了31 篇原创文章 · 获赞 69 · 访问量 130万+

猜你喜欢

转载自blog.csdn.net/u014789708/article/details/82852171