文章目录
ruby-sass
基于Ruby语言开发而成,因此安装sass前需要安装Ruby
Ruby是日本人开发的
node-sass lib-sass (弃用)
- https://github.com/sass/node-sass
- 不需要依赖Ruby
- LibSass and Node Sass are deprecated.
- Use Dart Sass instead.
dart-sass(推荐)
- https://github.com/sass/dart-sass
- Dart Sass is available, compiled to JavaScript, as an npm package. You can install it globally using
npm install -g sass
which will provide access to the sass executable. - You can also add it to your project using
npm install --save-dev sass
.
https://www.sass.hk/guide/
sass语法
https://sass.bootcss.com/documentation/syntax
Sass 支持两种不同的语法。两种语法可以互相加载,所以 选择哪一种语法取决于你和你的团队
- SCSS 语法使用 .scss 文件扩展名。除了极少部分的例外, 它是 CSS 的超集,也就是说 所有有效的 CSS 也同样都是有效的 SCSS 。 由于其与 CSS 的相似性,它是最容易上手的语法, 也是最流行的语法。
- 缩进语法是 Sass 的原始语法,因此它使用文件 扩展名 .sass 。由于这个扩展名的原因,这种语法有时直接被称为 “Sass"。 缩进语法支持与 SCSS 相同的所有特性,但是它使用 缩进而不是花括号和分号来描述文档的格式。
下面主要介绍第一种scss语法
使用变量
- 变量声明->sass使用$符号来标识变量
与CSS属性不同,变量可以在css规则块定义之外存在。当变量定义在css规则块内,那么该变量只能在此规则块内使用。如果它们出现在任何形式的{…}块中(如@media或者@font-face块),情况也是如此:$highlight-color: #F90;
- 变量引用
$highlight-color: #F90;
.selected {
border: 1px solid $highlight-color;
}
/* 编译后 */
.selected {
border: 1px solid #F90;
}
- 变量名用中划线还是下划线分隔;个人喜好
嵌套CSS 规则
#content {
article {
h1 { color: #333 }
p { margin-bottom: 1.4em }
}
#content aside { background-color: #EEE }
}
/* 编译后 */
#content article h1 { color: #333 }
#content article p { margin-bottom: 1.4em }
#content aside { background-color: #EEE }
- 父选择器的标识符&;->嵌套的选择器里边应用一个类似于:hover的伪类
article a {
color: blue;
&:hover { color: red }
}
/* 编译后 */
article a { color: blue }
article a:hover { color: red }
- 群组选择器的嵌套;
.container {
h1, h2, h3 {margin-bottom: .8em}
}
/* 编译后 */
.container h1, .container h2, .container h3 { margin-bottom: .8em }
- 子组合选择器和同层组合选择器:>、+和~;
>
直接子元素+
同层相邻组合选择器~
同层全体组合选择器;不管它们之间隔了多少其他元素:
article {
~ article { border-top: 1px dashed #ccc }
> section { background: #eee }
dl > {
dt { color: #333 }
dd { color: #555 }
}
nav + & { margin-top: 0 }
}
/* 编译后 */
article ~ article { border-top: 1px dashed #ccc }
article > footer { background: #eee }
article dl > dt { color: #333 }
article dl > dd { color: #555 }
nav + article { margin-top: 0 }
- 嵌套属性
nav {
border: {
style: solid;
width: 1px;
color: #ccc;
}
}
/* 编译后 */
nav {
border-style: solid;
border-width: 1px;
border-color: #ccc;
}
导入SASS文件
静默注释
sass另外提供了一种不同于css标准注释格式/* ... */
的注释语法,即静默注释,其内容不会出现在生成的css文件中。
静默注释的语法跟JavaScriptJava等类C的语言中单行注释的语法相同,它们以//
开头,注释内容直到行末。
混合器重用样式
// 混合器使用@mixin标识符定义。
@mixin rounded-corners {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
// 然后就可以在你的样式表中通过@include来使用这个混合器
notice {
background-color: green;
border: 2px solid #00aa00;
@include rounded-corners;
}
使用选择器继承来精简CSS
//通过选择器继承继承样式
.error {
border: 1px solid red;
background-color: #fdd;
}
.seriousError {
@extend .error;
border-width: 3px;
}