CSS选择器的基本分类
CSS选择器是样式表语言中的核心组成部分,用于精准定位HTML文档中的元素并施加样式规则。选择器的分类方式多样,按匹配模式、组合关系或功能特性可划分为不同类型,每种选择器在特定场景下展现其独特价值。
基础选择器
基础选择器构成CSS选择器体系的基石,包括以下四种主要类型:
-
元素选择器
直接匹配HTML标签名称,优先级较低但覆盖范围广:p { color: #333; line-height: 1.5; }
-
类选择器
通过元素的class属性进行匹配,可重复使用且支持多类名:<!-- HTML --> <button class="btn btn-primary">提交</button>
.btn-primary { background-color: #0066cc; padding: 8px 16px; }
-
ID选择器
针对唯一性元素的高优先级选择器,常用于锚点定位:#header-nav { display: flex; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
-
通配选择器
匹配文档所有元素,常用于全局样式重置:* { margin: 0; box-sizing: border-box; }
属性选择器
通过元素属性进行精确匹配,支持多种匹配模式:
- 存在性匹配:
[disabled] { opacity: 0.6; cursor: not-allowed; }
- 值精确匹配:
input[type="password"] { font-family: monospace; }
- 子串匹配(^=起始值,$=结尾值,*=包含):
a[href^="https"]::after { content: "🔒"; margin-left: 2px; }
伪类选择器
基于元素状态或文档结构的动态选择器:
-
用户行为伪类
a:hover { text-decoration: underline; } input:focus { outline: 2px solid #4d90fe; }
-
结构伪类
li:nth-child(2n) { background: #f5f5f5; } :root { --main-color: #3498db; }
-
表单状态伪类
input:checked + label { font-weight: bold; } :valid { border-color: #2ecc71; }
伪元素选择器
创建虚拟元素进行特殊样式处理:
p::first-line {
font-variant: small-caps;
}
blockquote::before {
content: "“";
font-size: 3em;
opacity: 0.2;
}
组合选择器
通过连接符建立元素关系链:
-
后代组合器(空格)
article p { text-indent: 2em; }
-
子组合器(>)
ul > li { list-style-type: square; }
-
相邻兄弟组合器(+)
h2 + p { margin-top: 0; }
-
通用兄弟组合器(~)
h1 ~ div { border-top: 1px dashed #ccc; }
选择器优先级计算
当规则冲突时通过特异性(specificity)决定应用顺序,计算规则为:
- 内联样式:1000
- ID选择器:100
- 类/属性/伪类:10
- 元素/伪元素:1
示例:
#nav .item.active {} /* 100 + 10 + 10 = 120 */
body header#main h1 {} /* 1 + 100 + 1 = 102 */
选择器性能优化
高效选择器编写原则:
-
避免深层嵌套:
/* 不推荐 */ body div#wrapper ul li a {} /* 推荐 */ .nav-link {}
-
优先使用类选择器替代属性选择器:
/* 较慢 */ [data-status="active"] {} /* 更快 */ .active-item {}
-
限制通用选择器使用范围:
/* 影响性能 */ * {} /* 较好 */ .container * {}
现代CSS新增选择器
-
逻辑组合伪类
:is(section, article) h1 { font-size: 2rem; } :where(.dark-theme, .light-theme) button { padding: 12px; }
-
方向感知伪类
:dir(rtl) { text-align: right; }
-
范围限定选择器
@scope (.card) to (.footer) { :scope { border: 1px solid #eee; } }
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:CSS的三种引入方式
下一篇:CSS的层叠与继承机制