css_6_复合选择器_伪类选择器_结构伪类

常用的几种写法:

一.按所有兄弟元素计算

  1. 所有兄弟中的第一个

:first-child

  1. 所有兄弟中的最后一个

:last-child

  1. 所有兄弟中的第n个

: nth-child(n)

举例:

        /* 选中的是div的第一个儿子p元素(按照所有兄弟元素计算) */
        div>p:first-child {
            color: blue;
        }
        /* 选中的是div的最后一个儿子p元素(按照所有兄弟元素计算) */
        div>p:last-child {
            color: blue;
        }
        /* 选中的是div的第n个儿子p元素(按照所有兄弟元素计算) */
        div>p:nth-child(3) {
            color: blue;
        }
        /* 选中的是div的偶数个儿子p元素(按照所有兄弟元素计算) */
        div>p:nth-child(2n) {
            color: blue;
        }

二.按同类型的兄弟元素计算

  1. 所有同类型兄弟中的第一个

:first-of-type

  1. 所有同类型兄弟中的最后一个

:last-of-type

  1. 所有同类型兄弟中的第n个

:nth-of-type(n)

举例:

        /* 选中的是div的第一个儿子p元素(按照所有同类型兄弟元素计算) */
        div>p:first-of-type {
            color: blue;
        }       
        /* 选中的是div的最后一个儿子p元素(按照所有同类型兄弟元素计算) */
        div>p:last-of-type {
            color: blue;
        }       
        /* 选中的是div的第n个儿子p元素(按照所有同类型兄弟元素计算) */
        div>p:nth-of-type(5) {
            color: blue;
        }       

注意:

关于括号内n的写法:

  1. 0或不写:什么都不选
  2. n:选中所有子元素
  3. 正整数:选中对应序号的子元素
  4. 用公式,但必须是 an+b 的形式
    如:选中序号为偶数的子元素:2n(或 even)
    选中序号为奇数的子元素:2n+1(或 odd)
  5. -n+5:前五个数

举例:

        /* 选中的是div的偶数个儿子p元素(按照所有兄弟元素计算) */
        div>p:nth-child(2n) {
            color: blue;
        }

了解就行的写法:

  1. 所有兄弟元素中的倒数第n个

:nth-last-child(n)

  1. 所有同类型兄弟元素中的倒数第n个

:nth-last-of-type(3)

  1. 没有兄弟的元素

:only-child

  1. 没有同类型兄弟的元素

:only-of-type

  1. 根元素

:root

  1. 没有内容的元素

:empty
注意:空格也是内容

举例:

        /* 选中的是div的倒数第n个儿子p元素(按照所有兄弟元素计算) */
        div>p:nth-last-child(3) {
            color: blue;
        }   
        /* 选中的是div的倒数第n个儿子p元素(按照所有同类型兄弟元素计算) */
        div>p:nth-last-of-type(3) {
            color: blue;
        }   
        /* 选中的是没有兄弟的span元素 */
        span:only-child {
            color: blue;
        }   
        /* 选中的是没有同类型兄弟的span元素 */
        span:only-of-type {
            color: blue;
        }   
        /* 选中的是根元素 */
        :root {
            background-color: gray;
        }   
        /* 选中的是没有内容的div元素 */
        div:empty {
            width: 40px;
            height: 40px;
            background-color: blue;
        }   
  • 16
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值