【CSS】css选择器和css获取第n个元素(:nth-of-type(n)、:nth-child(n)、first-child和last-child)

一、css选择器

选择器 用法
选择器 用法
ID选择器 #myid
类选择器 .myclassname
标签选择器 div,h1,p等等
相邻选择器 h1+p(选择紧接在另一个元素后的元素)
兄弟选择器 h1~p(ul后的所有p兄弟元素)
子选择器 ul > li
后代选择器 li a
通配符选择器 *
属性选择器 a[rel=“external”]、a[target="_blank"等等]
伪类选择器 a:hover, li:nth-child等等
<div id="box">
    <p>1</p>
    <div>我是div</div>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
    <p>6</p>
</div>

二、:nth-of-type、:nth-child的区别

:nth-of-type(n):选择器匹配属于父元素的特定类型的第N个子元素

所有兄弟节点中找到第三个p标签背景为红色。所以,3背景为红。

  • nth-of-type(2n)表示选中偶数标签
  • nth-of-type(2n-1)表示选中奇数标签
  • nth-of-type(n+2)表示选中从第2个开始到最后
  • nth-of-type(-n+2)表示选择从0到2的标签,即小于3的标签。
#box p:nth-of-type(3) {
   
    background: red;
}

:nth-child(n):选择器匹配属于其父元素的第 N 个子元素,不论元素的类型

找父元素的第三个子元素,如果该子元素为p,则其变为黄色,如果,第三个子元素不是p元素,则没有子元素的背景变为黄色。

  • nth-child(2n)表示选中偶数标签
  • nth-child(2n-1)表示选中奇数标签
  • nth-child(n+2)表示选中从第2个开始到最后
  • nth-child(-n+2)表示选择从0到2的标签,即小于3的标签。
  • nth-last-child(2)表示选中倒数第2个标签
#box p:nth-child(3) {
   
   background: yellow;
}

:first-child:获取元素的第 1 个子元素

#box p:first-child {
   
		background: pink;
	}

:last-child:获取元素的最后一个个子元素

#box p:last-child {
   
   	background: green;
   }

效果

在这里插入图片描述

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-02 14:36:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-02 14:36:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-02 14:36:01       87 阅读
  4. Python语言-面向对象

    2024-02-02 14:36:01       96 阅读

热门阅读

  1. 【Python函数——详细介绍】

    2024-02-02 14:36:01       54 阅读
  2. ScheduledExecutorService总结

    2024-02-02 14:36:01       63 阅读
  3. 如何创建和使用索引?

    2024-02-02 14:36:01       58 阅读
  4. leetcode-top100链表专题一

    2024-02-02 14:36:01       58 阅读
  5. Python程序设计 基础数据类型

    2024-02-02 14:36:01       43 阅读