一个SCSS里mixin的使用例子
发布日期:2021-06-30 14:44:16 浏览次数:2 分类:技术文章

本文共 1695 字,大约阅读时间需要 5 分钟。

Mixins are the Sass equivalent of macros in other programming languages. If you’ve programmed before you could think of them as functions, procedures, or methods, but they aren’t technically any of these concepts because their function is to generate code at compile time not execute code at run time.

可以把mixins当成编程语言里的宏,但是技术上说,scss mixins用于在编译器生成代码,而不是在运行时执行代码。

一个例子:

a.button {
background: black; color: white; padding: 10px 20px; @include border-radius(5px);}

编译之后:

a.button {
background: black; color: white; padding: 10px 20px; -moz-border-radius: 5px; -webkit-border-radius: 5px; -ms-border-radius: 5px; -o-border-radius: 5px; -khtml-border-radius: 5px; border-radius: 5px;}

I used the @include directive to tell Sass that I wanted to call out to a mixin.

使用@include指令,告诉sass,需要在css里call out mixin. 通过括号传递参数。

看下border-radius的实现代码:

@mixin border-radius($radius) {
-moz-border-radius: $radius; -webkit-border-radius: $radius; -ms-border-radius: $radius; border-radius: $radius;}

一个mixin传递默认参数的做法:

@mixin border-radius($radius: 5px) {
...}

或者定义一个全局变量:

$default-border-radius: 5px !default;@mixin border-radius($radius: $default-border-radius) {
...}

scss mixin里还支持条件指令@if:

@mixin border-radius($radius: 5px, $moz: true, $webkit: true, $ms: true) {
@if $moz {
-moz-border-radius: $radius; } @if $webkit {
-webkit-border-radius: $radius; } @if $ms {
-ms-border-radius: $radius; } border-radius: $radius;}

上面的用法叫做keyword argument.

这样,如果项目里我们不考虑对IE的支持,只需要下面这样写就行了:

@include border-radius($ms: false);

而不用这种繁琐的写法:

@include border-radius(5px, true, true, true);

也不需要按照顺序传递参数:

@include border-radius($ms: false, $radius: 10px);

转载地址:https://jerry.blog.csdn.net/article/details/114035373 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:SAP Spartacus里的bootstrap button usage
下一篇:Firefox开发者工具里的CSS Flexbox Inspector

发表评论

最新留言

不错!
[***.144.177.141]2024年05月05日 11时37分45秒