CSS 伪类大全
CSS伪类详解::nth-child(an+b)/:nth-of-type/:first-child/:last-child/:only-child、:is()/:where()/:not()/:has()选择器列表、:enabled/:disabled/:checked/:indeterminate表单状态、:target/:focus-within/:focus-visible · 难度:入门 · +10XP
CSS 伪类大全 —— 用好选择器,少写JavaScript
CSS伪类可以让你在不写JS的情况下实现很多交互效果。今天系统梳理最常用的伪类。
结构伪类 —— 按位置选择
li:first-child { } /* 第一个子元素 */
li:last-child { } /* 最后一个子元素 */
li:nth-child(2n) { } /* 偶数项(2,4,6...)*/
li:nth-child(2n+1) { } /* 奇数项(1,3,5...)*/
li:nth-child(3) { } /* 第3个 */
li:only-child { } /* 唯一的子元素 */
li:first-of-type { } /* 同类型中第一个 */
状态伪类 —— 按交互状态选择
input:focus { } /* 获得焦点 */
input:checked { } /* 被选中(复选框/单选)*/
input:disabled { } /* 禁用状态 */
input:enabled { } /* 启用状态 */
input:invalid { } /* 验证不通过 */
input:required { } /* 必填字段 */
input:optional { } /* 可选字段 */
a:visited { } /* 已访问链接 */
动手练习
- 基础练习:做一个斑马纹表格——用:nth-child(even)给偶数行加灰色背景。
- 进阶应用:做一个星级评分组件——5个radio+label,用:checked和后续兄弟选择器实现纯CSS评分。
- 项目实战:用:focus-within伪类做一个搜索框——输入框获得焦点时,整个搜索区域放大并加阴影。