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元素 */

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

相关推荐
修己xj1 小时前
打造专属博文封面神器:一个开源免费的博文封面生成器ThisCover
前端
kyriewen1 小时前
面试8家前端岗位后,我发现了一个残酷的事实:AI不是加分项,是门槛
前端·javascript·面试
Fighting_p1 小时前
【面试 - el-select问题及解决】wujie 微前端下子系统 el-select 多选 filterable 过滤失效
前端
吃口巧乐兹1 小时前
AI 全栈时代,为什么要服务端使用 NestJs
前端
yingyima1 小时前
Redis 延迟任务队列:凌晨3点服务器报警的救星
前端
weiggle1 小时前
第三篇:可组合函数(Composable)——Compose 的基石
android·前端
前端环境观察室1 小时前
别只看 task success:AI Agent 浏览器自动化真正要补的是环境证据链
前端·后端
huakoh1 小时前
LangChain 实战:用混合检索啃下 1000 页 PDF,搭一个长文档问答 Agent
前端
Dazer0071 小时前
Edge 浏览器绕过 HTTPS 证书错误
前端·https·edge
元让_vincent2 小时前
Spark 2.0:面向 Web 的 3DGS 可视化与大场景渲染平台详解
前端·3d·spark·渲染·轻量化·3dgs·lod