基础
最后更新于:2022-04-01 10:47:51
话虽如此,混合宏确实非常有用,你应该学习使用它。经验告诉我们,如果你发现有一组 CSS 属性经常因同一个原因一起出现(非巧合),那么你就可以使用混合宏来代替。比如[Nicolas Gallagher的清除浮动](http://nicolasgallagher.com/micro-clearfix-hack/)应当放入一个混合宏的实例。
~~~
/// Helper to clear inner floats
/// @author Nicolas Gallagher
/// @link http://nicolasgallagher.com/micro-clearfix-hack/ Micro Clearfix
@mixin clearfix {
&::after {
content: '';
display: table;
clear: both;
}
}
~~~
另一个有效的实例是通过在混合宏中绑定 `width` 和 `height` 属性,可以为元素设置宽高。这样不仅会淡化不同类型代码间的差异,也便于阅读。
~~~
/// Helper to size an element
/// @author Hugo Giraudel
/// @param {Length} $width
/// @param {Length} $height
@mixin size($width, $height: $width) {
width: $width;
height: $height;
}
~~~
## 扩展阅读
* [Sass Mixins to Kickstart your Project](http://www.sitepoint.com/sass-mixins-kickstart-project/)
* [A Sass Mixin for CSS Triangles](http://www.sitepoint.com/sass-mixin-css-triangles/)
* [Building a Linear-Gradient Mixin](http://www.sitepoint.com/building-linear-gradient-mixin-sass/)