今日工作
- 前端界面的初步编写与数据模拟
- sass进阶学习
sass学习(二)
1、@import
CSS,Sass 都支持 @import 指令。
@import 指令可以让我们导入其他文件等内容。
- CSS @import 指令在每次调用时,都会创建一个额外的 HTTP 请求。
- 但,Sass @import 指令将文件包含在 CSS中,不需要额外的 HTTP 请求。
@import filename;
注意:包含文件时不需要指定文件后缀,Sass 会自动添加后缀 .scss。此外,你也可以导入 CSS 文件。
reset.scss 文件代码:
html,
body,
ul,
ol {
margin: 0;
padding: 0;
}
standard.scss 文件代码:(导入了reset.scss)
@import "reset";
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: red;
}
将以上代码转换为 CSS 代码:
html, body, ul, ol {
margin: 0;
padding: 0;
}
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: red;
}
2、Partials
Partials 是用来定义公共样式或者组件的样式的,专门用于被其他的 scss 文件 import进行使用的。
Partials 这样的文件,命名规范是以下划线开头的,这样的 scss 文件不会被编译成 css文件。
但是,在导入语句中我们不需要添加下划线。如_base.scss导入时,使用@import “base”;即可
注意:请不要将带下划线与不带下划线的同名文件放置在同一个目录下,比如,_colors.scss 和 colors.scss 不能同时存在于同一个目录下,否则带下划线的文件将会被忽略。
3、@mixin
@mixin 指令允许我们定义一个可以在整个样式表中重复使用的样式。
@include 指令可以将混入(mixin)引入到文档中。
定义混入
@mixin important-text {
color: red;
font-size: 25px;
font-weight: bold;
border: 1px solid blue;
}
注意:Sass 的连接符号 - 与下划线符号 _ 是相同的,也就是 @mixin important-text { } 与 @mixin important_text { } 是一样的混入。
使用混入
.danger {
@include important-text;
background-color: green;
}
混入可以包含混入
@mixin special-text {
@include important-text;
@include link;
@include special-border;
}
向混入传递变量
混入可以接受参数
/* 混入接收两个参数 */
@mixin bordered($color, $width) {
border: $width solid $color;
}
.myArticle {
@include bordered(blue, 1px); // 调用混入,并传递两个参数
}
.myNotes {
@include bordered(red, 2px); // 调用混入,并传递两个参数
}
也可以定义参数默认值
@mixin sexy-border($color, $width: 1in) {
border: {
color: $color;
width: $width;
style: dashed;
}
}
p { @include sexy-border(blue); }
h1 { @include sexy-border(blue, 2in); }
可变参数:使用...
来设置可变参数
@mixin box-shadow($shadows...) {
-moz-box-shadow: $shadows;
-webkit-box-shadow: $shadows;
box-shadow: $shadows;
}
.shadows {
@include box-shadow(0px 4px 5px #666, 2px 6px 10px #999);
}
浏览器前缀使用混入
实例:
@mixin transform($property) {
-webkit-transform: $property;
-ms-transform: $property;
transform: $property;
}
.myBox {
@include transform(rotate(20deg));
}
转化为css代码:
.myBox {
-webkit-transform: rotate(20deg);
-ms-transform: rotate(20deg);
transform: rotate(20deg);
}
@extend
@extend 指令告诉 Sass 一个选择器的样式从另一选择器继承。
如果一个样式与另外一个样式几乎相同,只有少量的区别,则使用 @extend 就显得很有用。
.button-basic {
border: none;
padding: 15px 30px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button-report {
@extend .button-basic;
background-color: red;
}
.button-submit {
@extend .button-basic;
background-color: green;
color: white;
}
变为css后:
.button-basic, .button-report, .button-submit {
border: none;
padding: 15px 30px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button-report {
background-color: red;
}
.button-submit {
background-color: green;
color: white;
}
使用 @extend 后,我们在 HTML 按钮标签中就不需要指定多个类 class=“button-basic button-report” ,只需要设置 class=“button-report” 类就好了。
@extend 很好的体现了代码的复用。
Sass 函数
Sass 定义了各种类型的函数,这些函数我们可以通过 CSS 语句直接调用。