Blogger Information
Blog 12
fans 0
comment 0
visits 6065
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
CSS入门之常用伪类选择器的使用方法总结
天空
Original
1394 people have browsed it

常用分组结构伪类

选择第一个元素

  1. .list > li:nth-of-type(1) {
  2. background-color: violet;
  3. }

选择第一个元素

  1. .list>li:first-of-type {
  2. background-color: green;
  3. }

:nth-of-type(1)===>:first-of-type

选择第8个元素

  1. .list > li:nth-of-type(8) {
  2. background-color: violet;
  3. }

选择最后一个元素

  1. .list>li:last-of-type {
  2. background-color: yellow;
  3. }

选中倒数第四个

  1. .list>li:nth-last-of-type(4) {
  2. background-color: red;
  3. }

上下文选择器/层级选择器

语法:

层级:>,空格
平级:+,~

  • 1.子元素选择器:>
  • 2.后代元素:空额
  • 3.相邻兄弟:+
  • 4.所有兄弟:~

伪类选择器计算

公式与说明:

  • :nth-of-type(an+b)
  • a:系数,[0,1,2,…]
  • n:[0,1,2,3,…]
  • b: 偏移量,从0开始
  • 注:计算出来的索引,必须有效,从1开始

实例1: 匹配第3个元素后面的所有兄弟元素

  1. .list> :nth-of-type(n+3) {
  2. background-color: green;
  3. }

计算过程:

  • 0+3=3
  • 1+3=4
  • 2+3=5

实例2: 匹配倒数3个元素

  1. .list> :nth-of-type(-n+3) {
  2. background-color: green;
  3. }

计算过程:

  • -0+3=3
  • -1+3=2
  • -2+3=1
  • -3+3=0

语法糖

  • 奇数(odd)
  • 偶数(even)

    实例3:匹配奇数列

    1. .list> :nth-of-type(odd) {
    2. background-color: lightgreen;
    3. }
    等效于
    1. .list> :nth-of-type(2n -1) {
    2. background-color: lightgreen;
    3. }
    计算过程:
  • 2*0-1=-1
  • 2*1-1=1
  • 2*2-1=3
  • 2*3-1=5
  • 实例4:匹配偶数列

    1. .list> :nth-of-type(even) {
    2. background-color: lightgreen;
    3. }
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post