1、代码简化
1.1、简化媒介查询
@mixin flex{display: flex;justify-content: center;align-items: center;
}
.header{width: 100%;@include flex;//可以这样引用
}
//加入参数
@mixin flex($layout){display: flex;justify-content: $layout;align-items: $layout;
}
.header{width: 100%;@include flex(start);
}
@mixin flex($layout){display: flex;justify-content: $layout;align-items: $layout;@content;//就是花括号里传过来的内容
}
.header{width: 100%;@include flex(start){gap: 10px;};
}
@mixin respondTo($name,$minWith,$maxWith) {@if $name== '手机' {@media(min-width: 320px) and (max-width: 480px) {@content}} @else if $name=='平板' {@media(min-width: 481px) and (max-width: 768px) {@content}}
}.header {@include respondTo('手机') {height: 50px;}@include respondTo('平板') {height: 80px;}
}
$breakPoints:('phone':(320px,480px),'pad':(481px,768px),'notebook':(769px,1024px),'desktop':(1025px,1200px),'tv':1201px,
);
@mixin respondTo($name,$minWith,$maxWith) {$bp:map-get($breakPoints,$name);//保存变量bp@if type-of($bp)=='list'{$min:nth($bp,1);$max:nth($bp,2);@media(min-width: $min) and (max-width: $max) {@content}} @else {@media(min-width: $bp) {@content}}
}
完全体
$breakPoints:('phone':(320px,480px),'pad':(481px,768px),'notebook':(769px,1024px),'desktop':(1025px,1200px),'tv':1201px,
);
@mixin respondTo($name,$minWith,$maxWith) {$bp:map-get($breakPoints,$name);//保存变量bp@if type-of($bp)=='list'{$min:nth($bp,1);$max:nth($bp,2);@media(min-width: $min) and (max-width: $max) {@content}} @else {@media(min-width: $bp) {@content}}
}.header {@include respondTo('phone') {height: 50px;}@include respondTo('pad') {height: 60px;}@include respondTo('notebook') {height: 80px;}
}
1.2、@for、@while、@each、自定义函数
@for
@for的用法不同于JS,Sass中的for有两种格式:
- @for $i from n through m 表示变量i 的范围是[n, m];
- @for $i from n to m 表示变量i 的范围是[n, m);
@while
@each
自定义函数
1.3、sass里的数学函数
目标需求
原样
sass编译成css,终端输入,-w表示监控源文件变化
sass index.scss index.css -x
布局位置其实就是角度不一样
@use 'sass:math';
$r:120px;
.menu-item:nth-child(1) {$deg:45deg;$x:$r * math.sin($deg);$y:-$r * math.cos($deg);//@debug $x;//可在终端打印transform: translate($x,$y);
}
@use 'sass:math';$r: 120px;
$n: 6; //数量
$step: 360deg/$n; //数量
@for $i from 1 through $n {.menu-item:nth-child(#{$i}) {$deg: $step*($i - 1);$x: $r * math.sin($deg);$y: $r * math.cos($deg);transform: translate($x, $y);}
}