sass是什么
- sass 是一种成熟的 css 拓展语言。兼容 css 语法,较为灵活,可以显著减少代码编写行数
- 常见的 sass 文件有两种后缀:.sass 或.scss。
- .sass 采用缩进格式,且不需要分号。.scss 写法采用经典的大括号类似的代码块的写法
.sass写法
.hello
width: 100px
height: 100px
border: 1px solid black
.scss写法
.hello {
color: red;
}
sass 常用功能
- 案例采用.scss 语法
1. 嵌套规则
sass 允许样式嵌套,外层选择器将作为内层选择器的父元素
<div class="hello">
<span class="text"> test </span>
</div>
<style scoped lang="scss">
.hello {
border: 1px solid black;
.text {
color: yellow;
}
}
</style>
2. 变量
sass 声明变量以$开头(区别于 less 的@)。
<div class="hello">
<span class="text"> test </span>
</div>
<style scoped lang="scss">
$red: #ff6262; // 变量
.text {
color: $red;
}
</style>
当变量值是字符串时,需要用#{}
<div class="hello">
<span class="text"> test </span>
</div>
<style scoped lang="scss">
$red: 'red'; // 变量
.text {
color: #{$red};
}
</style>
3.父元素标识&
&
必须是选择器第一个字符- 常用于写伪类(
:hover
、::after
等) - 或者是父元素选择器的一部分使用
伪类元素
<template>
<div class="hello">
<span class="hello-text"> test </span>
</div>
</template>
<style scoped lang="scss">
.hello {
&:hover {
background: red;
}
}
</style>
作为父元素选择器的一部分
<template>
<div class="hello">
<span class="hello-text"> test </span>
</div>
</template>
<style scoped lang="scss">
.hello {
&-text {
color: red;
}
}
</style>
混合器
- 混合器使用
@mixin
来定义,使用@include
来使用 - 常用于混合大段的样式。
- 比 class 更为灵活,接受参数传递($\color{red} {动态混合} $),并且支持默认参数
- 如果参数未传递,将会报错
<template>
<h1>h1</h1>
<h2>h2</h2>
<h3>h3</h3>
</template>
<style scoped lang="scss">
@mixin base($size: 15px) {
box-sizing: border-box;
padding: 10px;
width: 100px;
border: 1px solid yellow;
font-size: $size;
}
h1 {
@include base(20px);
color: red
}
h2 {
@include base(25px);
color: blue
}
h3 {
@include base(30px);
color: green
}
</style>
例如mixins解决1px边框问题
<style scoped lang="scss">
@mixin border_1px($color: red) {
$media: screen;
$feature: -webkit-min-device-pixel-ratio;
@media #{$media} and ($feature: 2) {
position: relative;
&::before {
content: " ";
position: absolute;
left: 0;
bottom: 0;
background-color: $color;
width: 100%;
height: 1px;
transform: scaleY(0.5);
}
}
@media #{$media} and ($feature: 3) {
position: relative;
&::before {
content: " ";
position: absolute;
left: 0;
bottom: 0;
background-color: $color;
width: 100%;
height: 1px;
transform: scaleY(0.333);
}
}
}
h1 {
@include border_1px(green);
}
h2 {
@include border_1px(red);
}
h3 {
@include border_1px(gray);
}
</style>
继承*
继承也可以用来混合大段的样式,与混合器的区别在于$\color{red} {混合器可以传递参数} $ ,而继承单纯用来复用大块样式
- 可以用来继承另一个选择器的样式
- 通过
@extend
继承
<style lang="scss" scoped>
.div {
background-image: url('./some.png');
background-repeat: no-repeat;
background-position: center center;
font-size: 20px;
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
color: red;
}
.page {
@extend .div
}
</style>
函数指令*
- 函数指令用来返回一个计算值,通过
@function
去定义一个函数 - 参与计算的元素为sassScript 数据类型
- 支持 sassScript运算法则
@function getBorder($dpr) {
@if $dpr == 2 {
@return "scaleY(" + 0.5 + ')';
} @else if $dpr == 3 {
@return "scaleY(" + 0.33 + ')';
} @else {
@return '';
}
}