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. :focus-visible 智能焦点
更智能的焦点状态管理,减少不必要的轮廓样式。
/* 只在键盘操作时显示焦点样式 */
button:focus-visible {outline:2px solid blue;outline-offset:2px;}
8. :empty 空元素处理
优雅处理空元素,无需额外的类名标记。
/* 隐藏空元素 */
section:empty {display: none;}
9. 相邻兄弟选择器组合
灵活使用+和~选择器,处理元素间关系。
/*选择相邻的列表项 */
li + li {
margin-top:1rem;
}
/* 选择之后的所有段落 */
h2 ~ p{
padding-left:1em;
}