继承(Extend)
Extend 让一个选择器继承另一个选择器的所有样式。
Sass Extend
基本语法
scss
// 被继承的选择器
.button {
padding: 10px 20px;
border: none;
cursor: pointer;
}
// 继承
.button-primary {
@extend .button;
background: blue;
color: white;
}
.button-danger {
@extend .button;
background: red;
color: white;
}
编译结果:
CSS
.button, .button-primary, .button-danger {
padding: 10px 20px;
border: none;
cursor: pointer;
}
.button-primary { background: blue; color: white; }
.button-danger { background: red; color: white; }
占位符选择器 %
scss
// 占位符选择器(不输出到 CSS)
%button-base {
padding: 10px 20px;
border: none;
}
.button-primary {
@extend %button-base;
background: blue;
}
// %button-base 不会出现在编译结果中
链式继承
scss
.base { color: #333; }
.extended { @extend .base; font-weight: bold; }
.more-extended { @extend .extended; font-size: 18px; }
// .more-extended 继承 .extended 的所有样式(包括从 .base 继承的)
Less Extend
基本语法
less
.button {
padding: 10px 20px;
border: none;
}
.button-primary {
&:extend(.button);
background: blue;
}
// 或简写
.button-secondary:extend(.button) {
background: gray;
}
继承多个选择器
less
.base1 { color: #333; }
.base2 { font-size: 14px; }
.combined:extend(.base1, .base2) {
font-weight: bold;
}
all 关键字
less
// 继承所有匹配的选择器
.warning:extend(.alert all) { }
// 匹配 .alert、.alert:hover、.alert.active 等
Extend vs Mixin
| 对比项 | Extend | Mixin |
|---|---|---|
| 编译结果 | 选择器合并 | 样式复制 |
| 代码体积 | 更小 | 可能重复 |
| 参数支持 | 不支持 | 支持 |
| 适用场景 | 共享样式,无参数 | 需要参数化 |
| 来源保留 | 保留选择器关系 | 独立输出 |
选择建议
scss
// 场景一:相同样式,无差异 → Extend
.icon {
display: inline-block;
width: 16px;
height: 16px;
}
.icon-home { @extend .icon; background: url(home.png); }
.icon-user { @extend .icon; background: url(user.png); }
// 场景二:样式需要参数 → Mixin
@mixin button($color) {
padding: 10px;
background: $color;
}
.btn-red { @include button(red); }
.btn-blue { @include button(blue); }
注意事项
避免过度使用
scss
// 差:复杂继承链
.a { }
.b { @extend .a; }
.c { @extend .b; }
.d { @extend .c; }
// 好:扁平继承
.base { }
.extended1 { @extend .base; }
.extended2 { @extend .base; }
避免继承嵌套选择器
scss
// 差:可能导致意外的选择器
.parent {
.child { color: red; }
}
.element {
@extend .child; // 可能产生 .parent .element 这样的选择器
}
// 好:使用扁平选择器或占位符
.child { color: red; }
.element { @extend .child; }
在媒体查询中限制
scss
// 无效:媒体查询内 extend 外部选择器
@media (min-width: 768px) {
.responsive {
@extend .button; // 不生效
}
}
// 有效:在相同媒体查询内
@media (min-width: 768px) {
.button { padding: 10px; }
.responsive { @extend .button; } // 生效
}
要点总结
- Extend 实现样式共享,编译后选择器合并
- Sass 用
@extend,Less 用:extend() - 占位符选择器
%不输出到 CSS,适合纯基类 - 无参数共享样式用 Extend,需参数用 Mixin
- 避免复杂继承链和嵌套选择器继承
📝 发现内容有误?点击此处直接编辑