ccforward / cc

Code & Blog
1.59k stars 193 forks source link

63.CSS 伪类选择器 #68

Open ccforward opened 7 years ago

ccforward commented 7 years ago

CSS 伪类选择器

写了那么多的伪类选择器,有必要做个笔记总结一下

:root

顾名思义 root 元素就是 html 元素

E:nth-child(n)

E 元素不是其父元素的第 n 个子元素

E:nth-last-child(n)

E 元素是其父元素的倒数第 n 个子元素

p:nth-last-child(1)p:last-child

E:nth-of-type(n)

属于父元素的特定类型的第 n 个子元素的每个元素

E:nth-last-of-type(n)

属于父元素的特定类型的倒数第 n 个子元素的每个元素

E:first-child

第一个子元素 同 E:nth-child(1)

E:last-child

最后一个子元素 同 E:nth-last-child(1)

E:first-of-type

第一个子类型 同 E:nth-of-type(1)

E:last-of-type

最后一个子类型 同 E:nth-last-of-type(1)

E:only-child

E是其父元素的唯一子元素

E:only-of-type

E是其父元素的特定类型的唯一子元素

关于 child 和 type

p:nth-child(3n) 这个选择器会查询每一个父元素的第三个子元素, 如果是 p 元素就会匹配

p:nth-of-type(3n) 这个选择器会查询每一个父元素的第三个 p 子元素

E:empty

E元素没有子元素 因此像 <p>hello</p><p> </p> 并不会被 p:empty 匹配到,但是 <p></p><p><!-- comment --></p> 能够被匹配

这个选择器也会匹配一个空标签或自闭和标签 比如 <br><input />

CSS Selectors 4 中还会有 p:blank 来匹配 <p> </p>

E:lang(en)

匹配以语言 en 表示的元素E 比如


<div lang="en"><q>This English quote has a <q>nested</q> quote.</q></div>
<div lang="fr"><q>This French quote has a <q>nested</q> quote.</q></div>
<div lang="de"><q>This German quote has a <q>nested</q> quote.</q></div>
:lang(en) > q { quotes: '\201C' '\201D' '\2018' '\2019'; }
:lang(fr) > q { quotes: '« ' ' »'; }
:lang(de) > q { quotes: '»' '«' '\2039' '\203A'; }

E:not(exception)

『否定』选择器

匹配不符合参数选择器 exception 的元素

exception不能包含另外一个否定选择器

例如:

input:not([type=checkbox]):not([type=radio]) 会匹配除了 checkbox 和 radio 之外的所有 input 元素

<p>Some text.</p>
<p class="classy">Some other text.</p>
<span>One more text<span>
p:not(.classy) { color: red; }
body :not(p) { color: green; }

::before

为当前元素创建一个子元素作为伪元素, 位于该元素之前

默认为行内元素

::after

为当前元素创建一个子元素作为伪元素, 位于该元素之后

在 css2 中使用 E:after E:before

::first–letter

匹配第一个字母

::first–line

匹配元素的第一行

::selection

匹配选中的文字