我是靠谱客的博主 懵懂裙子,这篇文章主要介绍CSS-子元素选择器子元素选择器,现在分享给大家,希望可以做个参考。

子元素选择器

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> /*body > p:first-child { background-color: yellow; } p:last-child { background-color: yellow; } p:nth-child(odd) { background-color: yellow; } p:first-of-type { background-color: yellow; }*/ p:last-of-type { background-color: yellow; } </style> </head> <body> <span>我是span</span> <p>我是一个p标签</p> <p>我是一个p标签</p> <p>我是一个p标签</p> <p>我是一个p标签</p> <p>我是一个p标签</p> <p>我是一个p标签</p> <span>hello</span> </body> </html>

请添加图片描述

属性

  1. :first-child

可以选中第一个子元素

复制代码
1
2
3
4
body > p:first-child { background-color: yellow; }
  1. :last-child

可以选中最后一个子元素

复制代码
1
2
3
4
p:last-child { background-color: yellow; }
  1. :nth-child

可以选中第一个子元素

  • 该选择器后边可以指定一个参数,指定要选中第几个子元素
  • even 表示偶数位置的子元素
  • odd 表示奇数位置的子元素
复制代码
1
2
3
4
p:nth-child(odd) { background-color: yellow; }
  1. 其他
    • :first-of-type
    • :last-of-type
    • :nth-of-type

和:first-child 这些非常的类似
只不过 child,是在所有的子元素中排列
而 type,是在当前类型的子元素中排列

复制代码
1
2
3
4
5
6
7
p:first-of-type { background-color: yellow; } p:last-of-type { background-color: yellow; }

最后

以上就是懵懂裙子最近收集整理的关于CSS-子元素选择器子元素选择器的全部内容,更多相关CSS-子元素选择器子元素选择器内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部