首页 > 其他分享 >深入理解 伪类选择器 :nth-child(notation) 的参数

深入理解 伪类选择器 :nth-child(notation) 的参数

时间:2022-12-12 12:44:30浏览次数:70  
标签:notation 伪类 元素 list 2n 选择器 表达式

简介

:nth-child(notation) 是 CSS3 规范中新增的一个伪类选择器,用于选中符合 notaion 表达式的目标“子元素”。

该选择器左侧若有其他选择器,表示命中同时符合左侧条件以及 notation 的“子元素”,如:p:nth-child(n+2) 表示命中所有属于其父元素下顺序在第二位的 p 元素。

之前对于 notation 的原理一直不甚理解,只是简单地用过一些常见的表达式。今天详细了解了 w3c 官方对于该表达式的定义后,总算是有了较为清晰的认知。

notation 详解

notation 有两种表达形式:

  • 关键字:odd/even
  • An + B:其中 A 表示分组的长度,B 表示偏移量。

官方对 An + B 的定义如下:

Several things in CSS, such as the :nth-child() pseudoclass, need to indicate indexes in a list. The An+B microsyntax is useful for this, allowing an author to easily indicate single elements or all elements at regularly-spaced intervals in a list.

The An+B notation defines an integer step (A) and offset (B), and represents the An+Bth elements in a list, for every positive integer or zero value of n, with the first element in the list having index 1 (not 0).

For values of A and B greater than 0, this effectively divides the list into groups of A elements (the last group taking the remainder), and selecting the Bth element of each group.

The An+B notation also accepts the even and odd keywords, which have the same meaning as 2n and 2n+1, respectively.

The values of A and B can be negative, but only the positive results of An+B, for n ≥ 0, are used.

If both A and B are 0, the pseudo-class represents no element in the list.

点这里查看原文:https://w3c.github.io/csswg-drafts/css-syntax-3/#anb-microsyntax

重点从第二段开始,大致翻译如下:

An+B 表达式(原文是用“符号”这个名词)定义了一组整数——步长 A 和偏移量 B,代表第 An+B 个元素(可以为复数个)。其中 n 可以为任意的自然数,同时元素的起始索引是 1 而非 0。
当 A、B 的值大于 0,元素列表被拆分成大小为 A 的若干子集合(最后一个子集合会包含拆分后的全部剩余元素,也就是该集合的长度可以小于 A),并且命中每个子集合下面的第 B 个元素。
An+B 表达式同样接受 event/odd 关键字,其作用与 2n+1/2n 相同。
A、B 的值允许为负数,但只有当表达式的结果为正数时,选择器的样式才会生效。
若 A、B 同时为 0,则选择器不代表任何元素,因此不会生效。

其中,A 为 0 表示不分组。至于元素的起始索引为 1,这是为了符合日常中数学对于偶数的定义,否则若索引从 0 开始, 2n+1 命中的就是偶数位而非奇数位的子元素了。

看完上面的定义,大致验证了我的猜想,即:An+B 表达式被作为参数传给解析引擎,之后,解析引擎会尝试遍历可能符合条件的子元素集合,并从 n = 0 开始逐一验证每个子元素的索引能否满足 An+b 表达式的值(值首先必须大于 0)。

或者反过来讲更容易理解:验证 An+B = index 方程中(index 即为元素索引),未知数 n 是否为自然数(即 n ≥ 0)。若为真,则当前元素被命中。

标签:notation,伪类,元素,list,2n,选择器,表达式
From: https://www.cnblogs.com/cjc-0313/p/16975738.html

相关文章