sass使用基础

博客分类: 笔记 阅读次数: comments

sass使用基础

SASS 基础

安装:gem install sass

sass 是 css 的扩展,允许使用变量、潜逃规则、mixins、导入等众多功能,并完全兼容 css 语言。

sass 有两种语法:

第一种叫 SCSS(Sassy CSS),是 CSS3 语法的扩容版本。

第二种叫 Sass,语法较老,被称为缩排语法,提供了一种更简洁的 css 书写方式。

sass 的使用

三种使用方式:命令行工具,独立的 Ruby 模块,以及包含 Ruby on Rails 和 Merb 作为支持 Rack 的框架插件。

sass 文件的转换:sass input.scss:output.css

或者通过命令行监视:sass --watch input.scss:out.css

若是目录中有很多 Sass 文件,也可以用 Sass 监视整个目录:sass --watch app/sass:public/stylesheets

转换后的 css 文件排版方式(四种):

转化前:

#box {
  width: 100px;
  height: 100px;
  #small_box {
    width: 50px;
    height: 50px;
  }
}

第一种:嵌套方式(默认的转换方式)

在命令后加上--style nested

转化后:

#box {
  width: 100px;
  height: 100px;
}
#box #small_box {
  width: 50px;
  height: 50px;
}

第二种:常用方式

在命令后加上--style expanded

转化后:

#box {
  width: 100px;
  height: 100px;
}
#box #small_box {
  width: 50px;
  height: 50px;
}

第三种:紧凑方式

在命令后加上--style compact

转化后:

#box {
  width: 100px;
  height: 100px;
}
#box #small_box {
  width: 50px;
  height: 50px;
}

第四种:压缩方式

在命令后加上--style compressed

转化后:

#box {
  width: 100px;
  height: 100px;
}
#box #small_box {
  width: 50px;
  height: 50px;
}

sass 的变量声明

sass 的变量声明方式:

通过$+变量名+:+变量对应的值组成;

例:$color_blue:blue;

变量的调用:

可以被声明在花括号外,也可以声明在花括号里面:

例:

$color_blue: blue;
$color_yellow: yellow;

#box {
  $height: 200px;
  background: $color_blue;
  width: 100px;
  height: $height;
}

转换后:

#box {
  background: blue;
  width: 100px;
  height: 200px;
}

注意:在花括号外面声明的变量可以被其他地方调用;花括号内声明的只能在当前括号内使用

sass 的嵌套写法

在 css 中会有多次对某标签下的某个标签进行定义,会重复书写指向标签;sass 通过嵌套写法简化了书写的代码;

例:

#box .small {
  background: #000;
}
#box #small_box {
  width: 50px;
  height: 50px;
}
#box a {
  font-size: 20px;
}

在 sass 中可以写成:

#box {
  .small {
    background: #000;
  }
  #small_box {
    width: 50px;
    height: 50px;
  }
  a {
    font-size: 20px;
  }
}

&父选择器标识

​ 转化过程中,每解开一个嵌套就会用空格加父选择器连接;

​ 在嵌套写法中若是出现:hover 这一类时,可能会出现问题,空格隔开了:hover 和父选择器,将:hover 绑定在了这个选择器下的所有子标签上。

​ 用&号可以在解析时直接用父选择器替换&号

群组选择器

​ 可以将对应的嵌套写法的选择器组合起来

​ 例:

转化前:

#box,
#boss,
#bone {
  a {
    font-size: 20px;
  }
}

#box {
  a,
  p,
  i {
    font-size: 20px;
  }
}

转换后:

#box a,
#boss a,
#bone a {
  font-size: 20px;
}

#box a,
#box p,
#box i {
  font-size: 20px;
}

子组合选择器(> + ~)

​ 子组合选择器>选择一个元素的直接子元素

​ 同层相邻组合选择器+

​ 同层全体组合选择器~

导入 css 文件

​ @import 导入其他 scss 文件

​ 与 css 不同的是 css 中的@import 会导入 css 文件会在浏览器使用时才会去调用,使得速度减慢

​ sass 的@import 会在一开始就将导入的文件解析完成。

​ 注意:在 sass 中若是不希望将导入的文件也转化为 css 文件,可以根据规则在命名时使用_+文件名的方式来命名,导入时直接使用@import+文件名来导入其他 scss 文件;

注释

​ sass 中有三种注释()

/* *///以及/*! */