CSS常用选择器

CSS选择器用于选择HTML元素并为其应用样式。以下是CSS中最常用的选择器类型:

基本选择器

1.元素选择器 - 通过HTML标签名选择元素

html 复制代码
p { color: blue; }

2.类选择器 - 通过class属性选择元素(以.开头)

html 复制代码
.warning { color: red; }

3.ID选择器 - 通过id属性选择元素(以#开头)

html 复制代码
#header { background: gray; }

4.通用选择器 - 选择所有元素(*)

html 复制代码
* { margin: 0; padding: 0; }

组合选择器

5.后代选择器 - 选择某个元素内的所有特定后代(空格分隔)

html 复制代码
div p { font-size: 14px; }

6.子元素选择器 - 选择直接子元素(>分隔)

html 复制代码
ul > li { list-style: none; }

7.相邻兄弟选择器 - 选择紧接在另一个元素后的元素(+分隔)

html 复制代码
h1 + p { margin-top: 0; }

8.通用兄弟选择器 - 选择所有在指定元素之后的同级元素(~分隔)

html 复制代码
h2 ~ p { color: green; }

属性选择器

9.属性存在选择器 - 选择具有特定属性的元素

html 复制代码
[disabled] { opacity: 0.5; }

10.属性值选择器 - 选择属性等于特定值的元素

html 复制代码
[type="text"] { border: 1px solid #ccc; }

11.属性值包含选择器 - 选择属性值包含特定字符串的元素

html 复制代码
[class*="btn"] { padding: 5px 10px; }

12.属性值开头选择器 - 选择属性值以特定字符串开头的元素

html 复制代码
[href^="https"] { color: green; }

13.属性值结尾选择器 - 选择属性值以特定字符串结尾的元素

html 复制代码
[src$=".png"] { border: 1px solid #eee; }

伪类选择器

14.动态伪类

html 复制代码
a:link { color: blue; }        /* 未访问链接 */
a:visited { color: purple; }   /* 已访问链接 */
a:hover { text-decoration: underline; }  /* 鼠标悬停 */
a:active { color: red; }       /* 激活/点击时 */

15.结构伪类

html 复制代码
li:first-child { font-weight: bold; }  /* 第一个子元素 */
li:last-child { border-bottom: none; } /* 最后一个子元素 */
li:nth-child(2n) { background: #f5f5f5; }  /* 偶数子元素 */

16.表单伪类

html 复制代码
input:focus { outline: 2px solid blue; }
input:disabled { background: #eee; }
input:checked + label { font-weight: bold; }

伪元素选择器

17.伪元素

html 复制代码
p::first-line { font-weight: bold; }  /* 第一行 */
p::first-letter { font-size: 2em; }   /* 首字母 */
::before { content: "→"; }            /* 在元素前插入内容 */
::after { content: "!"; }             /* 在元素后插入内容 */

选择器组合

18.多重选择器 - 同时选择多个元素(逗号分隔)

html 复制代码
h1, h2, h3 { font-family: sans-serif; }

19.复合选择器 - 组合不同类型的选择器

html 复制代码
button.primary { background: blue; }  /* 类为primary的button元素 */

这些选择器可以灵活组合使用,以满足各种样式需求。

相关推荐
jeffwang33 分钟前
我做了个让 AI 看屏幕跑测试的工具,因为 Playwright 测不了我的 Flutter Web
前端
HSunR1 小时前
dify 搭建ai作业批改流
开发语言·前端·javascript
代码不加糖1 小时前
2026 跨境电商独立站实战:从 0 到 1 搭建高转化 SaaS 商城(附源码)
开发语言·前端·javascript
亲亲小宝宝鸭1 小时前
拖一拖控件,拖出个问卷(低代码平台)
前端·低代码
江南十四行2 小时前
ReAct Agent 基本理论与项目实战(一)
前端·react.js·前端框架
We་ct2 小时前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划
小呆呆6662 小时前
Codex 穷鬼大救星
前端·人工智能·后端
当时只道寻常3 小时前
Vue3 + IntersectionObserver 实现高性能图片懒加载
前端
sakiko_3 小时前
UIKit学习笔记3-布局、滚动视图、隐藏或显示视图
前端·笔记·学习·objective-c·swift·uikit
有一个好名字4 小时前
Agent Loop —— 一切从那个 while 循环开始
前端·javascript·chrome