文章目录
1. Learn Sass(快速入门)
1.1 预处理
有两个指令
sass --watch input.scss output.css
sass --watch app/sass:public/stylesheets
1.2 变量
定义和使用:
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
编译后:
body {
font: 100% Helvetica, sans-serif;
color: #333;
}
1.3 嵌套
sass允许css代码像html那样进行嵌套:
scss:
SCSS SYNTAX
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
css:
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
1.4 局部模块
可以将 sass/scss
代码分块,写在不同的文件中。
只要将这些文件的开头加上下划线,形如 _test.scss,Sass就不会对 _test.scss文件生成相应的 css
文件。
1.5 模块
可以使用 @use 来加载模块。
scss:
// _base.scss
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
// styles.scss
@use 'base';
.inverse {
background-color: base.$primary-color;
color: white;
}
css:
body {
font: 100% Helvetica, sans-serif;
color: #333;
}
.inverse {
background-color: #333;
color: white;
}
1.5 Mixins(混合类型)
(直译:)
css
里面的一些东西是非常冗长的,特别是加了厂商前缀之后。
一个 mixin 可以将你会重复使用的css打包成一个 group。
这会让你的代码中不出现重复代码。
(DRY DRY 全称:Don’t Repeat Yourself (摘自wikipedia),是指编程过程中不写重复代码,将能够公共的部分抽象出来,封装成工具类或者用“abstraction”类来抽象公有的东西,降低代码的耦合性,这样不仅提高代码的灵活性、健壮性以及可读性,也方便后期的维护或者修改。)
你也可以传参进去,去让你的 mixin 更加的灵活。
使用 @mixin 来定义,使用 @include 来使用。
scss:
@mixin theme($theme: DarkGray) {
background: $theme;
box-shadow: 0 0 1px rgba($theme, .25);
color: #fff;
}
.info {
@include theme;
}
.alert {
@include theme($theme: DarkRed);
}
.success {
@include theme($theme: DarkGreen);
}
css:
.info {
background: DarkGray;
box-shadow: 0 0 1px rgba(169, 169, 169, 0.25);
color: #fff;
}
.alert {
background: DarkRed;
box-shadow: 0 0 1px rgba(139, 0, 0, 0.25);
color: #fff;
}
.success {
background: DarkGreen;
box-shadow: 0 0 1px rgba(0, 100, 0, 0.25);
color: #fff;
}
1.6 拓展/继承(Extend/Inheritance)
使用 @extend 从一个选择器中共享一个css
属性集合。
以 **%**开头的选择器,只有使用之后才会被输出到 .css
文件中去。
@extend
后面只能跟选择器的 最外层选择条件,不支持
@extend .a .b // 不支持
/* This CSS will print because %message-shared is extended. */
%message-shared {
border: 1px solid #ccc;
padding: 10px;
color: #333;
}
// This CSS won't print because %equal-heights is never extended.
%equal-heights {
display: flex;
flex-wrap: wrap;
}
.message {
@extend %message-shared;
}
.success {
@extend %message-shared;
border-color: green;
}
.error {
@extend %message-shared;
border-color: red;
}
.warning {
@extend %message-shared;
border-color: yellow;
}
1.7 运算符
scss:
@use "sass:math";
.container {
display: flex;
}
article[role="main"] {
width: math.div(600px, 960px) * 100%;
}
aside[role="complementary"] {
width: math.div(300px, 960px) * 100%;
margin-left: auto;
}
css:
.container {
display: flex;
}
article[role="main"] {
width: 62.5%;
}
aside[role="complementary"] {
width: 31.25%;
margin-left: auto;
}