伪类(单冒号 :)根据元素的状态或位置来选择元素——这是普通 class 无法表达的,比如"鼠标悬停时"或"第一个子元素"。
状态伪类(交互)
css
{ : blue; }
{ : solid; }
{ : (); }
{ : ; }
{ }
{ }
链接的顺序很重要(LVHA)::link、:visited、:hover、:active。
li:first-child { } /* first li among its siblings */
li:last-child { } /* last one */
li:nth-child(2) { } /* the 2nd */
li:nth-child(odd) { } /* 1st, 3rd, 5th... — zebra striping */
li:nth-child(3n) { } /* every 3rd */
p:only-child { } /* a p that's the sole child */
:nth-child() 非常强大——2n(偶数)、2n+1(奇数)、3n(每隔三个)等等。
input:required { }
input:invalid { border-color: red; }
:is(h1, h2, h3) { } /* matches any — shortens selector lists */
.card:has(img) { } /* the "parent selector": a card that CONTAINS an img */
:not(.active) { } /* everything except .active */
伪类使用一个冒号(:hover,表示一种状态);伪元素使用两个(::before,表示一个生成的部分)。不要把它们混淆。
伪类让你无需额外标签或 JavaScript,就能为交互(hover/focus——对于可用、无障碍的 UI 至关重要)和结构(斑马纹、首/末元素)设置样式。
现代伪类(:has、:is、:focus-visible)解决了以往需要 JS 或重复选择器才能处理的问题。