网站首页 > 知识剖析 正文
本内容首发于工粽号:程序员大澈,每日分享一段优质代码片段,欢迎关注和投稿!
大家好,我是大澈!
本文约 600+ 字,整篇阅读约需 1 分钟。
今天分享一段优质 CSS 代码片段,使用CSS的伪类选择器实现了对特定位置列表项的样式控制。
老规矩,先阅读代码片段并思考,再看代码解析再思考,最后评论区留下你的见解!
li:nth-child(-n + 3) {
text-decoration: underline;
}
li:nth-child(n + 2):nth-child(-n + 5) {
color: #2563eb;
}
li:nth-last-child(-n + 2) {
text-decoration-line: line-through;
}
分享原因
这段代码展示了如何使用CSS的 nth-child 和 nth-last-child 伪类选择器来选择和样式化特定的列表项,这在复杂的样式需求中非常有用。
理解6和使用这些选择器,在项目中写样式的时候真的会是水到渠成,最起码不需要再费劲去想一个新类名了。
代码解析
1. li:nth-child(-n + 3)
n是从0开始的非负整数。
nth-child(-n + 3) 选择器会选中父元素的前三个子元素。
其中,-n + 3 表示选择从第一个元素开始直到第三个元素的所有子元素。
2. li:nth-child(n + 2):nth-child(-n + 5)
nth-child(n + 2) 选择器从第2个子元素开始选择。
nth-child(-n + 5) 选择器从第1个子元素选择到第5个子元素。
组合使用时,会选中从第2个到第5个子元素。
3. li:nth-last-child(-n + 2)
nth-last-child(-n + 2) 选择器从父元素的最后一个子元素向前数,选择倒数前两个子元素。
- end -
猜你喜欢
- 2024-11-21 Chrome:2023年CSS增加了哪些功能?
- 2024-11-21 WEB基础面试题——HTML、CSS
- 2024-11-21 手风琴特效这么飒,你能用 JavaScript 实现吗?
- 2024-11-21 css篇四 文本样式(上)
- 2024-11-21 Python Web全栈之旅12--Web前端●CSS扩展知识点汇总,建议收藏
- 2024-11-21 自己动手打造工具系列之自动刷新简历
- 2024-11-21 web前端:CSS的常用属性速查表
- 2024-11-21 css操作之常用技巧
- 2024-11-21 《锋利的jQuery》观后记
- 2024-11-21 了解CSS Flex:解析实例、用法和案例研究
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)