Mixin与include语法
@Mixin与@include语法
概述
- 在 Sass/SCSS 中, @mixin 用于定义可重复使用的样式, @include 用于调用(使用)这个 mixin.这种方法可以帮助简化样式表的管理和提高代码的重用性.
代码示例
@mixin
@include
编译后的 CSS
// 1. 定义一个基础 mixin(无参数)
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
// 2. 定义一个带参数的 mixin
@mixin size($width, $height) {
width: $width;
height: $height;
}
// 3. 定义一个带默认值的 mixin
@mixin font-style($size: 16px, $color: #333, $weight: normal) {
font-size: $size;
color: $color;
font-weight: $weight;
}
// 4. 定义一个带 @content 的 mixin(高级用法)
@mixin hover-style {
&:hover {
@content;
}
}
.box {
@include flex-center; // 使用无参数 mixin
@include size(200px, 200px); // 使用带参数 mixin
@include font-style(20px); // 使用带默认值 mixin(只改一个参数)
background: #f5f5f5;
@include hover-style { // 使用 @content
background: #ddd;
color: red;
}
}
.box {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
font-size: 20px;
color: #333;
font-weight: normal;
background: #f5f5f5;
}
.box:hover {
background: #ddd;
color: red;
}