SCSS 入门

158 阅读2分钟

起源

SASS 是2007年诞生,2016年成熟的一门类CSS语言。

SCSS 是在 SASS 基础上,把{ }:;都加回来的前端程序员能看得懂的类CSS语言。

原来的CSS:

body {
  color: red;
}
body p {
  font-size: 16px;
}

SASS:没有{ }:;,用空格缩进来代表格式

body
  color red
body p
  font-size 16px;

SCSS:可以在{ }里面嵌套写选择器,让代码更有逻辑性。

body {
  color: red;
  p {
    font-size: 16px;      
  } 
}

安装配置环境

安装代替 webpack 的 parcel

npm init -y
npm i -D parcel

运行 index.html

npx parcel index.html

功能

1 嵌套选择器

body {
  h1 {
    color: red;
  }
}

在请求的时候,自动将 SCSS 翻译成 CSS

image.png

2 变量

公用的参数可以存成变量,这样以后统一修改某个变量值非常方便

$grey: #666;
$border-width: 1px;
p {
  color: $gray;
    bprder: $border-width solid red;
}

最后显示出的结果会把所有变量替换成真实的值

image.png

3 mixin

如果希望某一处的样式可以轻松的到处使用,(比如为了方便调试,给一个元素加border),可以使用 @mixin 函数,然后再在想要使用该处样式的地方使用@include 函数进行调用。

$border-width: 1px;
@mixin debug($border-color) {
  border: $border-width solid $border-color;
}
body {
  h1 {
    @include debug(red);
  }
  ul {
    li {
      @include debug(green);
    }
  }
}

这样就可以在 CSS 里面写函数,让代码更有逻辑性

image.png

4 placehorder

mixin的缺点:@include 仅能做到机械式地拷贝代码,并不能真正的节省代码

@mixin box {
  box-shadow: 0 0 3px black;
  margin: 10px;
  background: white;
  border-radius: 4px;
}
h1 {
  font-family: 'Courier New';
  @include box;
}
ul {
  li {
    font-family: Arial;
    @include box;
  }
}

同样的样式被写了两遍

image.png 改用% 函数@extend %函数

%box {
  box-shadow: 0 0 3px black;
  margin: 10px;
  background: white;
  border-radius: 4px;
}
.nav {
  
  @extend %box;
}
.demo {
  height: 100px;
  @extend %box;
}

节省代码,将共有的样式写在并列选择器里

image.png

参考阅读