scss是什么?如何安装使用?有哪几大特性?

SCSS 是什么?

SCSS(Sassy CSS)是 Sass 的一种语法风格,它是 CSS 的超集,提供了 CSS 所没有的功能,但最终会被编译成普通 CSS 在浏览器中使用。

特点:

完全兼容 CSS,原来的 CSS 文件可以直接重命名为 .scss 使用。

支持 变量、嵌套、函数、混入、继承 等高级功能,使样式更易维护。

示例:

$primary-color: #007aff;

.button {

background-color: $primary-color;

&:hover {

background-color: darken($primary-color, 10%);

}

}

编译后会变成普通 CSS:

.button {

background-color: #007aff;

}

.button:hover {

background-color: #0062cc;

}

安装与使用

方法一:通过 npm 安装 Sass

如果你在 Node.js 项目 中:

# 安装 sass

npm install -D sass

然后可以通过命令行编译 SCSS:

# 编译 scss 文件为 css

npx sass style.scss style.css

# 或者实时监控文件变化

npx sass --watch style.scss:style.css

方法二:在 Vue 项目中

Vue CLI:直接安装 sass 后,在 .vue 文件中使用

SCSS 的几大特性

变量(Variables)

$primary: #007aff;

$padding: 10px;

.box {

color: $primary;

padding: $padding;

}

嵌套(Nesting)

.nav {

ul {

margin: 0;

li {

list-style: none;

}

}

}

混入(Mixins)

可以封装可重用的样式块:

@mixin flex-center {

display: flex;

justify-content: center;

align-items: center;

}

.box {

@include flex-center;

}

继承(Inheritance / Extend)

一个类可以继承另一个类的样式:

.button {

padding: 10px;

border-radius: 5px;

}

.primary-btn {

@extend .button;

background-color: blue;

}

运算(Operations)

$width: 100px;

$height: $width / 2;

.box {

width: $width;

height: $height;

}

函数(Functions)

内置函数如 darken(), lighten(), percentage(),也可以自定义函数:

.box {

background-color: lighten(#007aff, 20%);

}