[Sass][Visual Studio] SASS 语法介绍1 (Variable, Mixin, and Nest structure)

简单介绍使用方法


目录

1. SASS 基本介绍与安装 (An introduction to SASS and Using SASS with Visual Studio) 
2. SASS 语法介绍1 (Variable, Mixin, and Nest structure)
3. SASS 语法介绍2 (Import, Extend, Comment, error , and @debug and @warn)
4. SASS 进阶使用 (Mathematical calculations, Selector(%), Parent selectors, List)
5. SASS 进阶使用 (Media, color function, If condition, loop(@for, @each), key-value mapping )
6. SASS 实践 : Refactor MVC base website CSS

 

前言

这一篇我们简单介绍Variable、Mixin与Nest structure。
程序如下:

Sass Demo

 
 
$div-width : 150px;
$div-padding :10px 10px 10px 10px;

body {

}



.first-div{
    width: $div-width;
    padding: $div-padding ;
    background-color: #b6ff00;
}

.second-div{
    width: $div-width;
    padding: $div-padding ;
    background-color: #ff6a00;
}

Variable

有别于CSS,您可以在.scss中使用变量,增加程序可读性。变量的方法是加上'$',
例如:$button-width 与 $sidebar-padding。
Unlike CSS, you can use variable in .cscc file for increasing code readability.
You can use variable by '$', such as $button-width and $sidebar-padding

范例如下:
我们设定了$div-width 和 $div-padding,提供给.first-div与.second-div使用。
Demo as below:
We added $div-width and $div-padding in ".first-div" and ".second-div"

结果:
Result:

Mixin

您可以使用@mixin 与 @inculde,减少重复的程序区块。
You can use @mixin and @inculde for reducing duplication.

Step.1 建立@mixin basic-div-attribute
           Create @mixin basic-div-attribute
Step.2 将重复程序区块移入@mixin basic-div-attribute
           Move code section(width and padding) in @mixin basic-div-attribute

Step.3 在.frist-div与.second-div内加上 @include basic-div-attribute
            Add @include basic-div-attribute in  ".first-div" and ".second-div"

Nest structure

我们加上程序如下:
Then, we add code as below:

Sass Demo

 
 

Nest Struction Demo

hello
$div-width : 150px;
$div-padding :10px 10px 10px 10px;

body {

}

.first-div{
    width: $div-width;
    padding: $div-padding ;
    background-color: #b6ff00;
}

.second-div{
    width: $div-width;
    padding: $div-padding ;
    background-color: #ff6a00;
}

.third-div{
    @include basic-div-attribute;
    background-color: #00ffff;
}

.third-div H3{
    color: #ff0000;
}

.third-div div {
    background-color: #ff6a00;
}

.third-div div p  {
    color: #00ffff;
}


在css,我们遇到阶层架构的时候,可能需要这样写:
in css, style as below:


在scss中,你可以写成巢状结构,增加可读性
In scss, you can use nest structure as below (increasing readability)


这三种在scss特有的语法,在保存文件后,会自动转译成为正式的css语法,
产生.css与min.css。
After you save scss file, Variable, Mixin, and Nest structur will be compiled to .css and min.css.
As below:

文件下载(Demo download):

连结:https://dl.dropboxusercontent.com/u/13585157/SassDemo2.zip

参考数据

  1. 使用SCSS来加速写CSS吧 - http://blog.visioncan.com/2011/sass-scss-your-css/
  2. simplifying css in visual studio with sass https://app.pluralsight.com/library/courses/simplifying-css-visual-studio-sass/table-of-contents
  3. wiki - Sass https://zh.wikipedia.org/wiki/Sass_(%E6%A0%B7%E5%BC%8F%E8%A1%A8%E8%AF%AD%E8%A8%80)