How to use mixin in Sass
Some things in CSS are a bit tedious to write, especially with CSS3 and the many vendor prefixes that exist. A mixin lets you make groups of CSS declarations that you want to reuse throughout your site. You can even pass in values to make your mixin more flexible. A good use of a mixin is for vendor prefixes.
# Define
@mixin borderRadius {
border-radius: 5px;
-webkit-border-radius;5px;
-moz-border-radius:5px;
}
# @include to use the borderRadius
h1{
font-size: 28px;color: #333;
@include borderRadius;
}
# after compile the css as below
h1 {
font-size: 28px;
color: #333;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
}
#scss
@mixin con-art {
margin: 20px;
h1{
font-size: 16px;color: #666;
}
h2{
font-size: 14px;color: #444;
}
}
footer{
font-size: 12px;
font-weight: 500;
@include con-art;
}
# After compile the css as below
footer {
font-size: 12px;
font-weight: 500;
margin: 20px;
}
footer h1 {
font-size: 16px;
color: #666;
}
footer h2 {
font-size: 14px;
color: #444;
}
.box {
-webkit-transform: rotate(30deg);
-ms-transform: rotate(30deg);
transform: rotate(30deg);
}
We can write like this
@mixin transform($property) {
-webkit-transform: $property;
-ms-transform: $property;
transform: $property;
}
.box { @include transform(rotate(30deg)); }
@mixin border-value($width: 1px, $color: #333, $style: solid) {
border-width: $width;
border-color: $color;
border-style: $style;
}
/*Without Arguments*/
h1 {
@include border-value;
}
/* Take Arguments*/
h2 {
@include border-value(2px, #666, dashed);
}
/*Keyword Arguments*/
h3 {
@include border-value($style: dashed, $width: 3px, $color: #999);
}
/*Without Arguments*/
h1 {
border-width: 1px;
border-color: #333;
border-style: solid;
}
/* Take Arguments */
h2 {
border-width: 2px;
border-color: #666;
border-style: dashed;
}
/*Keyword Arguments*/
h3 {
border-width: 3px;
border-color: #999;
border-style: dashed;
}
Useful Links
https://www.cnblogs.com/liulei-cherry/p/10083285.html https://sass-lang.com/documentation/at-rules/mixin https://juejin.cn/post/6844903491400400910#heading-7 https://zhuanlan.zhihu.com/p/100914552