目录

1. first-child

2. last-child

3. nth-child

4. first-of-type

5. last-of-type


 

1. first-child

功能是: 选中A元素父元素的第一个为A元素

来看代码

first-child,last-child,nth-child,first-of-type,last-of-type 用法first-child,last-child,nth-child,first-of-type,last-of-type 用法

图1中 这样的样式浏览器未发现样式改变

解释下样式:

p的first-child的意思是 选中p的父元素中第一个元素是 p的 元素

  1.  图1中 p的父元素是body
  2.  所以找Body的第一个元素
  3.  但是第一个元素是 span  ,所以这个选择不生效了

现在改成如下, 在body下第一个位置添加p元素 , 这时候就选中了

first-child,last-child,nth-child,first-of-type,last-of-type 用法first-child,last-child,nth-child,first-of-type,last-of-type 用法

父元素内的第一个元素必须是指定的元素才可以

 

再添加个代码

first-child,last-child,nth-child,first-of-type,last-of-type 用法first-child,last-child,nth-child,first-of-type,last-of-type 用法

p4也变红了 , 因为他是父元素div的一个元素,符合条件

first-child,last-child,nth-child,first-of-type,last-of-type 用法first-child,last-child,nth-child,first-of-type,last-of-type 用法

如果在p4的父元素第一行加入别的元素, 可见p4的样式又会不见

 

2. last-child

与first-child意义相反,选中的是父元素的最后一个元素 ,

参考 first-child 即可明白此元素意义

 

3. nth-child

功能: 选中A元素的父元素第n个位置的A元素

first-child,last-child,nth-child,first-of-type,last-of-type 用法first-child,last-child,nth-child,first-of-type,last-of-type 用法

此时第一个位置span 未变色,因为他不是p元素

first-child,last-child,nth-child,first-of-type,last-of-type 用法first-child,last-child,nth-child,first-of-type,last-of-type 用法

如果改成2,则发现第二个位置变色

nth-child() 参数可以填数字,关键字,公式

比如有 odd 奇数, even 偶数 , n索引(从0开始)

 

4. first-of-type

与 first-child 类似 , 但是first-of-type是以元素类型为列表,来选择的

first-child,last-child,nth-child,first-of-type,last-of-type 用法first-child,last-child,nth-child,first-of-type,last-of-type 用法

如图一: 选择的是p类型的第一个p,即符合左边选择器条件的第一个

 

 

5. last-of-type

 first-of-type 的相反意义

 

相关文章:

  • 2021-08-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-10
  • 2021-11-07
  • 2021-12-28
  • 2022-02-24
猜你喜欢
  • 2022-12-23
  • 2021-06-11
  • 2021-04-13
  • 2021-06-25
  • 2022-12-23
  • 2021-06-06
  • 2022-12-23
相关资源
相似解决方案