:nth-child基本用法

本文深入探讨了CSS选择器的使用,包括:first-child、:nth-child()、:last-child和:nth-of-type()等,详细解释了它们的区别和应用场景。通过实例展示了如何有效地选取和操作页面元素,提升网页布局和样式控制的精度。

:first-child 第1个元素
:nth-child(3n) 第3的倍数个元素
:nth-child(-n+3) 前3个元素
:nth-child(n+3) 从第3个开始
:nth-last-child(-n+3) 最后3个元素
:last-child 最后1个元素

:nth-of-type 用法相同

端开发中,`:nth-child()` 伪类是一种强大的 CSS 选择器,能基于元素在父元素中的位置进行样式控制。 `:nth-child()` 的权重是单个伪类的权重,若使用 `of S` 语法,其权重为单个伪类的权重加上 `S` 中权重最高的权重值 [^2]。以下通过具体示例展示其使用方法: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>:nth-child() Example</title> <style> /* 选择父元素下的第一个子元素 */ .country1:nth-child(1) { color: blue; } /* 为所有子元素添加默认样式 */ .country1 { color: red; } </style> </head> <body> <div> <div id="country1" class="country1">CHINA</div> </div> </body> </html> ``` 在上述代码中,`.country1:nth-child(1)` 选择了父元素下的第一个 `.country1` 类元素,并将其文本颜色设置为蓝色;而 `.country1` 选择了所有具有 `country1` 类的元素,设置其文本颜色为红色。由于 `:nth-child(1)` 优先级更高,第一个子元素最终显示为蓝色 [^2]。 还可以使用 `:nth-child()` 选择奇数或偶数子元素,示例如下: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>:nth-child() Odd/Even Example</title> <style> /* 选择父元素下的奇数子元素 */ ul li:nth-child(odd) { background-color: lightgray; } /* 选择父元素下的偶数子元素 */ ul li:nth-child(even) { background-color: lightblue; } </style> </head> <body> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> </ul> </body> </html> ``` 此代码中,`ul li:nth-child(odd)` 选择了无序列表中的奇数项,并将其背景颜色设置为浅灰色;`ul li:nth-child(even)` 选择了偶数项,将背景颜色设置为浅蓝色。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值