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

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

相关推荐
小屁孩大帅-杨一凡39 分钟前
一个简单点的js的h5页面实现地铁快跑的小游戏
开发语言·前端·javascript·css·html
读心悦43 分钟前
CSS 布局系统深度解析:从传统到现代的布局方案
前端·css
椒盐螺丝钉1 小时前
CSS盒子模型:Padding与Margin的适用场景与注意事项
前端·css
萧鼎2 小时前
构建全栈 Web 应用的新选择:NextPy 技术详解与实战指南
前端
这个一个非常哈2 小时前
VUE篇之自定义组件使用v-model
前端·javascript·vue.js
purpleseashell_Lili2 小时前
react 基本写法
java·服务器·前端
哎哟喂_!2 小时前
Node.js 循环依赖问题详解:原理、案例与解决方案
前端·chrome·node.js
热爱前端的小君同学3 小时前
长按拖拽移动的vue3组件
前端·javascript·vue.js
Rhys..3 小时前
如何禁止chrome自动更新
前端·chrome
巴巴_羊3 小时前
AJAX 使用 和 HTTP
前端·http·ajax