新一代CSS选择器:12个技巧让代码量减少70%

作者: jie 分类: CSS 发布时间: 2026-01-22 09:48

CSS选择器的使用技巧直接影响着我们的代码质量和维护效率。分享一些新一代的CSS选择器技巧,这些技巧不仅能让你的代码更简洁,还能提升样式表的可维护性。

1. :is() 选择器:组合选择的神器

:is()选择器可以将多个选择器分组,大幅减少重复代码。

/* 之前的写法 */
header p,
main p,
footer p {
	line-height: 1.6;
}

/* 使用:is()的写法 */
:is(header, main, footer) p {
	line-height: 1.6;
}

2. :where() 选择器:零特异性的福音

:where()的功能类似:is(),但特异性为0,让样式更容易被覆盖。

/* 特异性较高 */
article :is(header, footer) p {
	color: #333;
}

/* 特异性为0,更容易覆盖 */
article :where(header, footer) p {
	color: #333;
}

3. :has() 关系选择器:父元素选择的革命

:has()让我们终于可以基于子元素选择父元素。

/* 选择包含图片的段落 */
p:has(img) {
	display: flex;
	align-items: center;
}

/* 选择后面有标题的段落 */
p:has(+ h2) {
	margin-bottom: 2em;
}

4. 属性选择器通配符匹配

使用属性选择器的通配符匹配可以更灵活地选择元素。

/* 选择所有数据属性 */
[data-*="important"] {
	font-weight: bold;
}

/* 选择特定语言的元素 */
[lang|="en"] {
	font-family: 'Arial', sans-serif;
}

5. :nth-child() 进阶用法

使用公式选择特定元素,实现复杂的选择模式。

/* 选择第4个之后的所有元素 */
li:nth-child(n+4) {
	margin-top: 1em;
}

/* 选择前5个元素 */
li:nth-child(-n+5) {
	font-weight: bold;
}

6. :not() 多条件排除

新版:not()支持多个选择器,大大增强了排除能力。

/* 排除多个类型的元素 */
div:not(.excluded, .special, [data-type="temp"]) {
	background: #f5f5f5;
}

7. 层叠层级管理 @layer

使用@layer管理样式优先级,减少特异性战争。

@layer base,
components,
utilities;

@layer base {
	/* 基础样式*/
}

@layer components {
	/*组件样式*/
}

8. :focus-visible 智能焦点

更智能的焦点状态管理,减少不必要的轮廓样式。

/* 只在键盘操作时显示焦点样式 */
button:focus-visible {
	outline: 2px solid blue;
	outline-offset: 2px;
}

9. :empty 空元素处理

优雅处理空元素,无需额外的类名标记。

/* 隐藏空元素 */
section:empty {
	display: none;
}

10. 相邻兄弟选择器组合

灵活使用+~选择器,处理元素间关系

/* 选择相邻的列表项 */
li+li {
	margin-top: 1rem;
}

/* 选择之后的所有段落 */
h2~p {
	padding-left: 1em;
}

11. 复合选择器优化

组合多个选择器条件,实现精确匹配。

/* 同时满足多个条件 */
button[type="submit"]:not(:disabled):hover {
	transform: translateY(-1px);
}

12. 媒体查询容器

使用容器查询,实现更精确的响应式设计。

@container sidebar (min-width: 400px) {
	.widget {
		display: grid;
		grid-template-columns: 1fr 1fr;
	}
}

发表回复