混合(Mixin)
Mixin 定义可复用样式块,支持参数,提高代码复用性。
Sass Mixin
定义与使用
scss
// 定义
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
// 使用
.container {
@include flex-center;
}
// 编译结果
// .container { display: flex; justify-content: center; align-items: center; }
带参数
scss
// 带默认参数
@mixin button($bg: blue, $color: white) {
background: $bg;
color: $color;
padding: 10px 20px;
border: none;
}
// 使用默认值
.btn {
@include button;
}
// 传入参数
.btn-primary {
@include button(blue, white);
}
// 关键字参数
.btn-warning {
@include button($bg: orange, $color: black);
}
可变参数
scss
@mixin box-shadow($shadows...) {
box-shadow: $shadows;
}
.card {
@include box-shadow(0 1px 3px rgba(0,0,0,0.1), 0 2px 5px rgba(0,0,0,0.2));
}
内容块 @content
scss
@mixin respond-to($breakpoint) {
@media (min-width: $breakpoint) {
@content;
}
}
.container {
@include respond-to(768px) {
display: flex;
}
}
// 编译结果
// @media (min-width: 768px) { .container { display: flex; } }
Less Mixin
定义与使用
less
// 定义(与类选择器相同)
.flex-center() {
display: flex;
justify-content: center;
align-items: center;
}
// 使用
.container {
.flex-center();
}
带参数
less
// 带默认参数
.button(@bg: blue, @color: white) {
background: @bg;
color: @color;
padding: 10px 20px;
}
// 使用
.btn-primary {
.button(blue, white);
}
.btn-warning {
.button(orange, black);
}
@arguments 变量
less
.box-shadow(@x, @y, @blur, @color) {
box-shadow: @arguments;
}
.card {
.box-shadow(0, 2px, 4px, rgba(0,0,0,0.1));
}
模式匹配
less
// 根据参数匹配不同 mixin
.border(dark) {
border: 1px solid #333;
}
.border(light) {
border: 1px solid #ccc;
}
.card-dark {
.border(dark);
}
.card-light {
.border(light);
}
Sass 与 Less 对比
| 特性 | Sass | Less |
|---|---|---|
| 定义语法 | @mixin name | .name() 或 .name |
| 调用语法 | @include name | .name() 或 .name |
| 默认参数 | $var: value | @var: value |
| 可变参数 | $args... | @args... |
| 内容块 | @content | @{content} 不支持 |
| 模式匹配 | 无 | 支持 |
实用 Mixin 示例
清除浮动
scss
@mixin clearfix {
&::after {
content: '';
display: table;
clear: both;
}
}
.container {
@include clearfix;
}
文本截断
scss
@mixin ellipsis($lines: 1) {
@if $lines == 1 {
white-space: nowrap;
text-overflow: ellipsis;
} @else {
display: -webkit-box;
-webkit-line-clamp: $lines;
-webkit-box-orient: vertical;
}
overflow: hidden;
}
.title {
@include ellipsis; // 单行
}
.desc {
@include ellipsis(3); // 三行
}
响应式断点
scss
@mixin mobile {
@media (max-width: 767px) {
@content;
}
}
@mixin tablet {
@media (min-width: 768px) and (max-width: 1023px) {
@content;
}
}
.container {
padding: 20px;
@include mobile {
padding: 10px;
}
}
要点总结
- Mixin 实现样式复用,支持参数传递
- Sass 用
@mixin定义,@include调用 - Less 用类选择器语法定义,直接调用
- Sass 的
@content支持内容块,适合媒体查询封装 - 常用于:浏览器前缀、响应式断点、常用布局模式
📝 发现内容有误?点击此处直接编辑