SCSS 快速入门以及使用

255 阅读5分钟

SCSS 是什么?

SCSS(Sassy CSS)是 Sass 的一种语法格式,它兼容标准的 CSS,并引入了许多高级特性,使得编写 CSS 更加高效、模块化和可维护。

SCSS 的主要特性以及常用写法

变量 $variable

$primary-color: #007bff;

.btn-primary {
  background-color: $primary-color;
}
// 输出
// .btn-primary {}

嵌套规则,最好不要超过 3 层

.navbar {
  background: #333;

  ul {
    list-style: none;

    li {
      display: inline-block;
    }
  }
  // 父选择器 &
  &--primary {
    background: blue;
  }

  &:hover {
    background-color: darkblue;
  }
}
// 输出
// .navbar {}
// .navbar ul {}
// .navbar ul li {}
// .navbar--primary {}
// .navbar:hover {}

混合宏 @mixin@include

@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  @include flex-center;
}
// 输出
// .container {
//   display: flex;
//   justify-content: center;
//   align-items: center;
// }

扩展继承 @extend

%btn-base {
  padding: 10px 20px;
  border-radius: 4px;
}

.btn-success {
  @extend %btn-base;
  background-color: green;
}

.btn-fail {
  @extend %btn-base;
  background-color: red;
}

// 输出
// .btn-fail, .btn-success {
// 	padding: 10px 20px;
// 	border-radius: 4px;
// }
// .btn-success {
// 	background-color: green;
// }
// .btn-fail {
// 	background-color: red;
// }

条件判断 @if

@mixin set-background($color) {
  // lightness scss 的内置函数
  @if lightness($color) > 30% {
    background-color: #000;
  } @else {
    background-color: #fff;
  }
}
.c-333333 {
  @include set-background(#333333);
}
.c-ff0000 {
  @include set-background(#ff0000);
}

// 输出
// .c-333333 {
// 	background-color: #fff;
// }
// .c-ff0000 {
// 	background-color: #000;
// }

循环控制 @for@each

  • @each 的语法格式
    • 遍历列表(List)
      @each $item in <List> {
        // 样式逻辑
      }
      
    • 遍历对象(Map)
      @each $key, $value in <Map> {
        // 样式逻辑
      }
      
@for $i from 1 through 2 {
  .col-#{$i} {
    width: 100% / 2 * $i;
  }
}
// 输出
// .col-1 {
// 	width: 50%;
// }
// .col-2 {
// 	width: 100%;
// }

// @each 遍历 List
$sizes: 16px, 24px, 32px;

@each $size in $sizes {
  .icon-#{$size} {
    font-size: $size;
  }
}
// 输出
// .icon-16px {
//   font-size: 16px;
// }
// .icon-24px {
//   font-size: 24px;
// }
// .icon-32px {
//   font-size: 32px;
// }

// @each 遍历 Map
$colors: (
  'primary': #007bff,
  'success': #28a745,
  'danger': #dc3545,
);

@each $name, $color in $colors {
  .text-#{$name} {
    color: $color;
  }
}

// 输出
// .text-primary {
// 	color: #007bff;
// }
// .text-success {
// 	color: #28a745;
// }
// .text-danger {
// 	color: #dc3545;
// }

函数 @function

@function calculate-rem($size) {
  $rem-size: $size / 16px;
  @return #{$rem-size}rem;
}

body {
  font-size: calculate-rem(18px);
}

// 输出
// body {
// 	font-size: 1.125rem;
// }

BEM 命名规范

  • 使用 BEM(Block Element Modifier)命名规范
// _bem.scss
@mixin b($block) {
  .#{$block} {
    @content; // 块级样式
  }
}

@mixin e($element) {
  &__#{$element} {
    @content; // 元素样式
  }
}
@mixin m($modifier) {
  &--#{$modifier} {
    @content; // 修饰符样式
  }
}
@mixin multi-m($modifiers...) {
  @each $modifier in $modifiers {
    &--#{$modifier} {
      @content;
    }
  }
}
@include b('card') {
  padding: 20px;

  @include e('header') {
    font-size: 18px;

    @include m('highlight') {
      // 嵌套修饰符
      color: #1890ff;
    }
    @include multi-m('success', 'warning') {
      font-size: 24px;
    }
  }
}

// 编译结果:
// .card { padding: 20px; }
// .card__header { font-size: 18px; }
// .card__header--highlight { color: #1890ff; }
// .card__header--success {	font-size: 24px; }
// .card__header--warning {	font-size: 24px; }

内置函数

颜色函数

颜色调整

函数作用示例
lighten($color, $amount)增加亮度lighten(#333, 20%) → #666
darken($color, $amount)降低亮度darken(#ccc, 30%) → #666
saturate($color, $amount)增加饱和度saturate(#999, 50%) → #ff6666
desaturate($color, $amount)降低饱和度desaturate(red, 100%) → #808080
adjust-hue($color, $degrees)调整色相adjust-hue(red, 120deg) → #00ff00
mix($color1, $color2, $weight)混合颜色mix(red, blue, 50%) → #800080

透明度处理

函数作用示例
opacify($color, $amount)增加不透明度opacify(rgba(0,0,0,0.5), 0.2) → rgba(0,0,0,0.7)
transparentize($color, $amount)降低不透明度transparentize(red, 0.3) → rgba(255,0,0,0.7)

颜色模型转换

函数作用示例
hue($color)获取 HSL 色相值hue(#ff0000) → 0deg
saturation($color)获取 HSL 饱和度saturation(#ff0000) → 100%
lightness($color)获取 HSL 亮度lightness(#ff0000) → 50%
red($color)获取 RGB 红色通道值red(#ff0000) → 255
green($color)获取 RGB 绿色通道值green(#00ff00) → 255
blue($color)获取 RGB 蓝色通道值blue(#0000ff) → 255

数值函数

函数作用示例
percentage($number)将小数转百分比percentage(0.5) → 50%
round($number)四舍五入round(3.6) → 4
ceil($number)向上取整ceil(3.2) → 4
floor($number)向下取整floor(3.8) → 3
abs($number)绝对值abs(-10) → 10
min($numbers...)取最小值min(1, 2, 3) → 1
max($numbers...)取最大值max(1px, 2px) → 2px
random($limit?)生成随机数random(10) → 0~10的整数

字符串函数

函数作用示例
quote($string)添加引号quote(abc) → "abc"
unquote($string)移除引号unquote("abc") → abc
str-length($string)字符串长度str-length("hello") → 5
str-slice($string, $start, $end)截取子串str-slice("hello", 2, 4) → "ell"
to-upper-case($string)转大写to-upper-case(abc) → ABC
to-lower-case($string)转小写to-lower-case(ABC) → abc

列表函数

函数作用示例
length($list)列表长度length(1px 2px) → 2
nth($list, $n)获取第 N 项nth(a b c, 2) → b
join($list1, $list2)合并列表join(a b, c d) → a b c d
append($list, $val)追加元素append(a b, c) → a b c
index($list, $value)查找索引index(a b c, b) → 2

Map 函数

函数作用示例
map-get($map, $key)获取键值map-get((a:1, b:2), a) → 1
map-merge($map1, $map2)合并 Mapmap-merge((a:1), (b:2)) → (a:1, b:2)
map-keys($map)获取所有键map-keys((a:1, b:2)) → a, b
map-values($map)获取所有值map-values((a:1, b:2)) → 1, 2
map-has-key($map, $key)检查键是否存在map-has-key((a:1), a) → true

选择器函数

函数作用示例
selector-append($selectors...)拼接选择器selector-append(".a", ".b") → .a.b
selector-nest($selectors...)嵌套选择器selector-nest(".a", ".b") → .a .b
selector-unify($selector1, $selector2)合并选择器用于复杂选择器逻辑

其他函数

函数作用示例
if($condition, $if-true, $if-false)三元条件if(true, a, b) → a
inspect($value)返回值的字符串表示inspect(1px) → "1px"
type-of($value)获取值的类型type-of(10px) → number
unit($number)获取单位unit(10px) → "px"
unitless($number)检查是否无单位unitless(10) → true

Meta 模块函数(高级)

函数作用
meta.global-variable-exists($name)检查全局变量是否存在
meta.module-variables($module)获取模块的变量列表
meta.function-exists($name)检查函数是否存在

Scss 写法的对比

scss 中 @extends@mixin @include 的区别?

  1. @extend:
  • 用途: @extend 用于将一个选择器的样式应用到另一个选择器上。它会将多个选择器合并到一个 CSS 规则集中。
  • 优点: 减少生成的 CSS 文件大小,因为样式只会被定义一次。
  • 缺点: 可能会导致选择器组合变得复杂,难以调试。
// scss 源文件
%footer-style {
  box-sizing: content-box;
  height: 88rpx;
  padding-bottom: env(safe-area-inset-bottom);
}
.footer-place {
  @extend %footer-style;
}
.footer-fixed {
  position: fixed;
  left: 0;
  bottom: 0;
  @extend %footer-style;
}

// css 编译后文件
.footer-place,
.footer-fixed {
  box-sizing: content-box;
  height: 88rpx;
  padding-bottom: env(safe-area-inset-bottom);
}
.footer-fixed {
  position: fixed;
  left: 0;
  bottom: 0;
}
  1. @mixin 和 @include:
  • 用途: @mixin 用于定义可重用的样式块,可以包含参数。
  • 优点: 提供更大的灵活性,可以传递参数来定制样式。
  • 缺点: 可能会导致生成的 CSS 文件变大,因为每个@include 都会生成独立的样式规则。
// scss 源文件
@mixin footer-styles($height: 88rpx) {
  box-sizing: content-box;
  height: $height;
  padding-bottom: env(safe-area-inset-bottom);
}
.footer-place {
  @include footer-styles;
}
.footer-fixed {
  position: fixed;
  left: 0;
  bottom: 0;
  @include footer-styles;
}

// css 编译后文件
.footer-place {
  box-sizing: content-box;
  height: 88rpx;
  padding-bottom: env(safe-area-inset-bottom);
}
.footer-fixed {
  position: fixed;
  left: 0;
  bottom: 0;
  box-sizing: content-box;
  height: 88rpx;
  padding-bottom: env(safe-area-inset-bottom);
}

scss 中 @use@import 的区别?

在 SCSS(Sass)中,@use@import 都用于导入样式文件,但它们的行为和推荐使用场景有明显区别:

  1. @import
  • 功能:将一个 SCSS 文件的内容导入到当前文件中,并将其变量、混合(mixins)、函数等全局暴露出来。

  • 缺点:

    • 每次导入都会重新加载整个文件内容,可能导致重复代码和性能问题。
    • 所有导入的变量、mixin、函数都进入全局命名空间,容易造成命名冲突。
  • 示例

    @import 'path/to/file';
    
  1. @use
  • 功能:引入 SCSS 模块,支持模块化开发。它会将导入的文件作为一个模块,仅加载一次,并通过命名空间访问其内容。

  • 优点:

    • 提高性能,避免重复加载。
    • 避免命名冲突,因为默认不会污染全局命名空间。
  • 示例: 然后可以通过 vars.$primary-colorvars.mixin-name() 的方式调用。

    @use './variables' as vars;
    
  1. @forward
  • 功能:与 @use 类似,但 @forward 允许你导出变量、mixins 和 functions,使其可以在其他地方使用。

  • 示例:

    scss/
    ├── mixins/
    │   ├── _buttons.scss
    │   └── _layout.scss
    └── index.scss
    
    // _buttons.scss
    @mixin btn-primary {
      background: blue;
      color: white;
    }
    
    // _layout.scss
    @mixin container {
      width: 100%;
      max-width: 1200px;
      margin: 0 auto;
    }
    
    // index.scss
    @forward 'mixins/buttons';
    @forward 'mixins/layout';
    
    // 其他文件使用
    @use '../scss/index' as theme;
    
    .my-button {
      @include theme.buttons.btn-primary;
    }
    
    .container {
      @include theme.layout.container;
    }
    
  1. @import, @use, @forward 对比

    功能@import@use@forward
    加载一次每次导入都重新加载只加载一次只加载一次
    避免命名冲突全局暴露默认不暴露,需显式指定命名空间默认不暴露,需显式指定命名空间
    支持版本所有>= 1.23.0>= 1.23.0
    主要用途兼容旧代码导入并使用模块转发模块内容

在线转换

在线 Scss 转换为 css