scss基础用法学习

71 阅读1分钟

1.scss变量的基础使用

//sass变量 
$baseColor: red; 
$count: 100px; 
.item { 
    color: $baseColor; // 向下取整floor函数 
    font-size: floor($count/3); 
    }
  1. scss的for函数基本使用
// sass函数 for函数 
@for $i from 1 through 36{ 
    .item#{$i}{ 
        color: hsl($i * 10, 50%, 50%); 
    } 
 }
  1. scss的each函数基本使用
 $words: 'a','b', 'c', 'd', 'e', 'f', 'g'; 
 $max: 1920px; // 根据不同屏幕大小改变文字的值 
 .be::after{ 
     content: 'be a'; 
     font-size: 20px; 
     color: red; 
     // each 函数 
     @each $word in $words { 
         @media screen and (max-width: $max) {
             content: 'be #{$word}'; 
         } 
         $max: $max - 10px 
     }
}

4.scss函数的基本使用

// sass函数封装 
@function getShadow($n){ 
    // #{}接受变量 
    $shadow: '#{random(100)}vw #{random(100)}vh #fff';
    @for $i from 2 through $n{
        $shadow: '#{$shadow}, #{random(100)}vw #{random(100)}vh #fff' 
    } 
    // 返回值@return unquote:去除引号 
    @return unquote($shadow) 
}

5.scss读取对象值、if/else使用、type-of类型判断以及mixin混入使用

// 读取scss对象值 // 值为数组或对象时用()包裹 
$breakpoints: ( 
    'phone': ( 320px, 480px ), 
    'pad': ( 481px, 768px ), 
    'tv': 1020px 
); 
// map-get(obj, key) 获取obj下的key值 
$bp: map-get($breakpoints, 'phone'); // (320px,480px), 
// nth(arr, n) 获取数组arr中的第n个值 
$min: nth($bp, 1); // 320px 
// type-of(key) 判断key值得类型 list: 数组格式,例如$breakpoints中的phone对应的值 
@if type-of($bp) == 'list' {
    // ..... 
} 
@else{
    // ..... 
} 
// 定义mixin混入方法 $breakname:传入参数--phone 
@mixin respond-to($breakname){ 
    // ... 
    // @ content为使用mixin方法时后面{}传入的值--height: 50px; 
    @content 
}; 
// 通过@include 使用mixin 
.item{ 
    @include respond-to('phone'){ 
        height: 50px; 
    } 
}

6.scss读取一个多层嵌套的值以及封装scss方法

// 定义一个多层嵌套值 
$dataMap: ( 
    name: ( 
        firstName: 'long', 
        secondName: 'rui' 
    ), 
    age: ( 
        ageCurrent: 18, 
        ageLastYear: 17 
    ) 
); 
// 定义一个获取具体值得方法 
@function getValue($key1, $key2){ 
    $key1Value: map-get($dataMap, $key1); 
    @return map-get($key1Value, $key2) 
} 
.item{ 
    &::after{ 
        content: getValue('name', 'firstName') 
    } 
}

7.使用@use方法导入scss模块

@use 'sass:math'; 
@use 'sass:color' // 可不导入 
$deg: 60dge; 
$x: $r * math.sin($deg);//计算sin值 
.item{ 
    color: lighten(#ccc, 10%); //变亮 
    background: darken(#ccc, 10%); //变暗 
}

8.scss模块化

// 编译时: 编译为css后会使用当前语法,因为css内置了@import 
@import url('../../sss.scss'); 
// 运行时: @import与@use都可以,但建议使用@use 
@import '../demo.scss'; 
@use '../demo.scss'; 
//如果demo.scss中有变量,可以通过——demo.$变量名 来使用 
//也可以自定义名,通过——custom.$变量名 来使用 
@use '../demo.scss' as custom; 
// demo.scss中如果需要私有变量 不希望被外部访问,则使用_,例如$_n,则在外部不能使用$_n变量

9.sass继承类与占位符

// 继承 编译后有.tip{...} 
.tip{ 
    color: yellow; 
} 
.tip1{ 
    background: red; 
    @extend .tip;// =>等同于color: yellow; 
} 
// 占位符 编译后没有%tip{...} 
%tip{ 
    color: yellow; 
} 
.tip1{ 
    background: red; 
    @extend %tip;// =>等同于color: yellow; 
}