在 App.vue 中导入 scss
<style lang="scss">
/* 每个页面公共样式 */
@import '/style/base.scss';
</style>
一、变量
/* scss */
$color-base: red;
.box{
background-color: $color-base;
}
/* ==> css */
.box{
background-color: red;
}
二、四则运算
三、多值变量
/* scss */
$linkColor: #08c #333;
a{
color: nth($linkColor, 1);
&:hover{
color: nth($linkColor, 2);
}
}
/* ==> css */
a {
color: #08c;
}
a:hover {
color: #333;
}
四、each 循环
字体、背景图
/* scss */
$title: (h1: 32rpx, h2: 28rpx, h3: 24rpx, h4: 18rpx)
@each $key, $size in $title {
#{$key} { font-size: $size; }
}
/* ==> css */
h1 { font-size: 32rpx; }
h2 { font-size: 28rpx; }
h3 { font-szie: 24rpx; }
h4 { font-szie: 18rpx; }
五、mixin 混合
自定义代码块、边距
/* scss 自定义代码块 */
@mixin center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
/* scss 等参数 */
@mixin margin($top, $right, $bottom, $left) {
margin: $top $right $bottom $left;
}
.box {
@include margin(10px, 10px, 20px, 20px);
}
/* ==> css */
.box { margin: 10px 10px 20px 20px; }
/* scss 默认参数 */
@mixin opacity($val: 1) {
opacity: $val;
}
.box { @include opacity(); }
.box1 { @include opacity(0.5); }
/* ==> css */
.box { opacity: 1; }
.box1 { opacity: 0.5; }
六、extend 继承
/* scss */
.active {
background-color: #f66;
color: #fff;
}
.success {
@extend .active;
font-size: 30px;
}
/* ==> css */
.active, .success {
background-color: #f66;
color: #fff;
}
.success { font-size: 30px; }
七、if 条件
/* scss */
$type: nopass;
.name {
@if $type == pass {
color: green;
} @else if $type == nopass {
color: red;
} @else {
color: black;
}
}
/* ==> css */
.name {
color: red;
}
八、for 循环
/* scss */
@for $i from 1 through 3 {
.item-#{$i} { width: 20% * $i; }
}
/* ==> css */
.item-1 { width: 20%; }
.item-2 { width: 40%; }
.item-3 { width: 60%; }
补充
父选择器标识符 &
在scss中,需要在子级使用父级选择器
/* scss */
.box {
width: 100rpx;
height: 100rpx;
&:before {
content: '',
}
}
/* ==> css */
.box {
width: 100rpx;
height: 100rpx;
}
.box:before {
content: ''
}
子级选择器中的 >
、~
、+
>
:子代选择器(某元素中所有子代元素)
div>em {}
/* 选中 div 中所有子代 em 元素 */
<div>
<em></em> // 选中
<span>
<em></em> // 未选中
<span>
<div>
<em></em> // 选中
</div>
<div>
:后代选择器(某元素中所有后代元素)
div em {}
/* 选中 div 中所有后代 em 元素 */
<div>
<em></em> // 选中
<span>
<em></em> // 选中
<span>
<div>
<em></em> // 选中
</div>
<div>
+
:相邻兄弟选择器 (某元素后相邻的第一个兄弟元素)
li+li {}
/* li后的紧挨着第一个li */
<ul>
<li></li> // 未选中
<li> // 选中
<li></li> // 选中
<li>
<li></li> // 选中
<span></span>
<li></li> // 未选中
</ul>
~
:兄弟选择器(某元素后所有同级的指定元素)
li~li {}
/* li 后的所有同级li(处于同一个父元素下) */
<ul>
<li></li> // 未选中
<li></li> // 选中
<span></span>
<li></li> // 选中
</ul>