sass基础

一、sass的安装和启用

  1. 安装ruby和sass  sass -v  可以显示版本号即可;

  2. 命令行cd到指定的sass文件所在的文件夹目录下,然后sass --watch main.scss;

    sass生成的css会有四种不同的样式

    --style nested

    --style expanded

    --style compact

    --style compressed

    使用时;在命令行输入sass --watch main.scss --style compressed这种格式即可。尝试一下十分容易理解。

二、变量

  1. 普通变量和默认变量的声明和调用 

//普通变量
$fontSize: 12px; //声明
body{
    font-size:$fontSize; //调用
}
//默认变量:默认变量的价值在进行组件化开发的时候会非常有用。
$baseLineHeight:1.5 !default;
body{
    line-height: $baseLineHeight; 
}

  2. 全局变量和局部变量

$color: orange !default;//定义全局变量(在选择器、函数、混合宏...的外面定义的变量为全局变量)

.block {
  color: $color;//调用全局变量
}
em {
  $color: red;//定义局部变量
  a {
    color: $color;//调用局部变量
  }
}
span {
  color: $color;//调用全局变量
}

三、嵌套

   1. 选择器嵌套

//HTML结构:
<header>
<nav>
    <a href=“##”>Home</a>
    <a href=“##”>About</a>
    <a href=“##”>Blog</a>
</nav>
<header>
//Sass: 
nav {
  a {
    color: red;
    //&:上一级选择器
    header & {
      color:green;
    }
  }  
}

  2. 属性嵌套

//属性嵌套
.box {
  border: {
   top: 1px solid red;
   bottom: 1px solid green;
  }
}

  3.伪类嵌套

.clearfix{
    &:before,
    &:after {
        content:"";
        display: table;
      }
    &:after {
        clear:both;
        overflow: hidden;
      }
}

 四、混合

  1.  无参混合宏

//不带参数的混合宏
@mixin border-radius{
    -webkit-border-radius: 5px;
    border-radius: 5px;
}
//调用:
.box {
  @include border-radius;
}

  2.无默认值带参混合宏

//无默认值的带参混合宏
@mixin border-radius($radius){
    -webkit-border-radius: $radius;
    border-radius: $radius;
}
//调用:
.box {
  @include border-radius(3px);
}

  3.有默认值带参混合宏

//带默认值
@mixin border-radius($radius:3px){
  -webkit-border-radius: $radius;
  border-radius: $radius;
}
//调用
.box {
  @include border-radius(50%);//或者@include border-radius;
}

   4. 多个参数带参混合宏

//带多个参数(例如经典居中)
@mixin center($width,$height){
   $width;
  height: $height;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -($height) / 2;
  margin-left: -($width) / 2;
}
//调用
.box-center {
  @include center(500px,300px);
}
//参数过多时的复杂混合宏:
@mixin box-shadow($shadow...) {
  @if length($shadow) >= 1 {
    @include prefixer(box-shadow, $shadow);
  } @else{
    $shadow:0 0 4px rgba(0,0,0,.3);
    @include prefixer(box-shadow, $shadow);
  }
}
//当 $shadow 的参数数量值大于或等于“ 1 ”时,表示有多个阴影值,反之调用默认的参数值“ 0 0 4px rgba(0,0,0,.3) ”。

//调用声明的混合宏:
.box {
  @include box-shadow(0 0 1px rgba(#000,.5),0 0 2px rgba(#000,.2));
}
原文地址:https://www.cnblogs.com/sowhite/p/6362365.html