混入 @mixin
约 536 字大约 2 分钟
2025-04-01
混入(Mixins)是 Sass 中最强大的功能之一,它允许你定义可重用的样式块,并在整个项目中重复使用,支持参数传递,极大提高了代码的复用性和维护性。
一、基础混入
1、定义混入
@mixin button-style {
padding: 10px 20px;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}
2、使用混入
.primary-button {
@include button-style;
background-color: blue;
color: white;
}
二、带参数的混入
1、基本参数
@mixin box($width, $height) {
width: $width;
height: $height;
}
.element {
@include box(100px, 200px);
}
2、默认参数
默认参数的格式类似于 JavaScript 函数的默认参数:
@mixin alert($color, $padding: 10px) {
color: $color;
padding: $padding;
border: 1px solid $color;
}
.warning {
@include alert(orange); // 使用默认padding
}
.error {
@include alert(red, 15px); // 覆盖默认padding
}
三、参数列表(可变参数)
@mixin shadows($shadows...) {
box-shadow: $shadows;
}
.card {
@include shadows(0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.2);
}
四、内容块(@content)
混入可以接收样式块,其用法类似于 Vue 中的插槽(v-slot):
@mixin media($width) {
@media (min-width: $width) {
@content;
}
}
.container {
width: 100%;
@include media(768px) {
width: 750px;
}
}
编译为:
.container {
width: 100%;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
五、实际应用示例
1、创建灵活的按钮混入
@mixin button($bg-color, $text-color: white, $hover-darken: 15%) {
background-color: $bg-color;
color: $text-color;
padding: 0.5em 1em;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
&:hover {
background-color: darken($bg-color, $hover-darken);
}
}
.primary-btn {
@include button(blue);
}
.secondary-btn {
@include button(gray, black, 10%);
}
2、响应式设计混入
@mixin respond-to($breakpoint) {
@if $breakpoint == phone {
@media (max-width: 600px) {
@content;
}
} @else if $breakpoint == tablet {
@media (max-width: 900px) {
@content;
}
} @else if $breakpoint == desktop {
@media (min-width: 901px) {
@content;
}
}
}
.header {
font-size: 2rem;
@include respond-to(phone) {
font-size: 1.5rem;
}
}
六、总结
- 命名要有意义:使用动词或动作短语命名混入
- 保持单一职责:每个混入只做一件事
- 合理使用参数:参数不宜过多(通常不超过 5 个)
- 适当使用默认值:提高混入的灵活性
- 文档注释:为复杂混入添加注释说明
混入功能让 Sass 真正强大起来,通过合理使用可以大幅减少重复代码,提高开发效率和维护性。
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于