SASS用法整理

Author Avatar
ibcLee 2月 02, 2016

SASS作为CSS预处理器,在最近的开发中经常使用,但是大多数的时候也只是用到其中的嵌套和变量,对于其他的一些方法都很少用到,这次主要是把SASS的所有用法过一遍,在日后的开发中很会省很多事,更何况SASS的学习成本很低,没有特别难理解的地方,记住就会用了。简单的一些用法就不再提了。

1.编译

作为前端,放在本地开发的时候,经常会先对SASS文件进行编译,在引入编译之后的CSS文件,监听并编译方法:

// watch a file
sass –watch input.scss:output.css
// watch a directory
sass –watch app/sass:public/stylesheets

2.变量

变量可以镶嵌在字符串中,必须要写在#{}中

1
$side: left;
.rounded {
  border-#{$side}-radius: 5px;
}
1
//多值变量
$linkColor: #08c #333 !default;//第一个值为默认值,第二个鼠标滑过值
a{
  color:nth($linkColor,1);

  &:hover{
    color:nth($linkColor,2);
  }
}

3.属性嵌套

1
//sass style
//-------------------------------
.fakeshadow {
  border: {
    style: solid;
    left: {
      width: 4px;
      color: #888;
    }
    right: {
      width: 2px;
      color: #ccc;
    }
  }
}

//css style
//-------------------------------
.fakeshadow {
  border-style: solid;
  border-left-width: 4px;
  border-left-color: #888;
  border-right-width: 2px;
  border-right-color: #ccc; 
}

4.继承

1
//class2继承class1
.class1 {
 	border: 1px solid #ddd;
}
.class2 {
  @extend .class1;
  font-size:120%;
}

5.Mixin

1
//定义代码块
@mixin left($value:10px){
	float:left;
	margin-left:$value;
}
div{
	@include left(20px);
}

6.条件语句

1
p{
	@if 1+1==2
		{border:1px solid;}
	@if 5<3
		{border:2px dotted}
	@if lightness($color)>30%{
		background-color:#000;
	}@else{
		abckground-color:#fff;
	}
}

7.循环语句

1
@for $i from 1 to 10{
	.border-#{$i}{
		border:#{$i}px solid blue;
	}
}
1
$i:6;
@while $i>0{
	.item-#{$i}{
		width:2em * $i;
	}
	$i:$i-2;
}
1
//each命令
//sass style
//-------------------------------
$animal-data: (puma, black, default),(sea-slug, blue, pointer),(egret, white, move);
@each $animal, $color, $cursor in $animal-data {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
    border: 2px solid $color;
    cursor: $cursor;
  }
}

//css style
//-------------------------------
.puma-icon {
  background-image: url('/images/puma.png');
  border: 2px solid black;
  cursor: default; 
}
.sea-slug-icon {
  background-image: url('/images/sea-slug.png');
  border: 2px solid blue;
  cursor: pointer; 
}
.egret-icon {
  background-image: url('/images/egret.png');
  border: 2px solid white;
  cursor: move; 
}

8.自定义函数

1
@function double($n){
	@return $n * 2;
}
#sidebar{
	width:double(5px);
}