Z
ZHANK
选择器进阶

伪类选择器

:hover/:focus/:first-child/:last-child/:nth-child()/:not() 等常用伪类

伪类选择器

伪类表示元素的特殊状态——如悬停、聚焦、第一个子元素。

学完本章你将: 掌握 :hover/:focus/:first-child/:last-child/:nth-child()/:not()。


状态伪类

css
a:hover { color: red; }         /* 鼠标悬停 */
input:focus { border-color: blue; }  /* 聚焦 */
button:active { transform: scale(0.98); }  /* 按下 */

结构伪类

css
/* 第一个/最后一个子元素 */
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }

/* 第 n 个子元素 */
li:nth-child(2) { color: red; }         /* 第 2 个 */
li:nth-child(odd) { background: #f9f9f9; }   /* 奇数 */
li:nth-child(even) { background: #eee; }      /* 偶数 */
li:nth-child(3n+1) { color: blue; }           /* 第 1,4,7... 个 */

/* 同类型第 n 个 */
p:nth-of-type(2) { font-style: italic; }

否定伪类

css
/* 排除特定元素 */
li:not(:last-child) { border-bottom: 1px solid #ddd; }
input:not([type="submit"]) { width: 100%; }

其他常用伪类

css
:first-of-type { }   /* 同类型第一个 */
:only-child { }      /* 唯一的子元素 */
:empty { }           /* 没有子元素(含文本) */
:checked { }         /* 选中的 checkbox/radio */
:disabled { }        /* 禁用的表单元素 */