sass教程随笔(四)

来源:互联网 发布:vb cpu序列号 编辑:程序博客网 时间:2024/05/21 09:41

sass 作为一个 css 预编译语言 也有很多类似与js的函数算法 用于操作大量的css 

1.条件语句

@if 用来进行判断
 p {    @if 1 + 1 == 2 { border: 1px solid; }    @if 5 < 3 { border: 2px dotted; }  }
配套的还的@else命令
@if lightness($color) > 30% {    background-color: #000;  } @else {    background-color: #fff;  }

2.循环语句

sass支持for循环
 @for $i from 1 to 10 {    .border-#{$i} {      border: #{$i}px solid blue;    }  }
sass也支持while循环
$i: 6;  @while $i > 0 {    .item-#{$i} { width: 2em * $i; }    $i: $i - 2;  }
each命令 作用与@for相似
@each $member in a, b, c, d {    .#{$member} {      background-image: url("/image/#{$member}.jpg");    }  }

3.自定义函数

sass允许用户自己编写函数
@function double($n) {    @return $n * 2;  }  #sidebar {    width: double(5px);  }

4.&操作符

在嵌套 CSS 规则时,有时也需要直接使用嵌套外层的父选择器,例如,当给某个元素设定 hover 样式时,或者当 body 元素有某个 classname 时,可以用 & 代表嵌套规则外层的父选择器
//scssa {  font-weight: bold;  text-decoration: none;  &:hover { text-decoration: underline; }  body.firefox & { font-weight: normal; }}//cssa {  font-weight: bold;  text-decoration: none; }a:hover {    text-decoration: underline; }body.firefox a {    font-weight: normal; }
& 必须作为选择器的第一个字符,其后可以跟随后缀生成复合的选择器,例如
//scss#main {  color: black;  &-sidebar { border: 1px solid; }}//css#main {  color: black; }#main-sidebar {    border: 1px solid; }

4.属性嵌套

有些 CSS 属性遵循相同的命名空间 (namespace),比如 font-family, font-size, font-weight 都以 font 作为属性的命名空间。为了便于管理这样的属性,同时也为了避免了重复输入,Sass 允许将属性嵌套在命名空间中,例如:
//scss.funky {  font: {    family: fantasy;    size: 30em;    weight: bold;  }}//css.funky {  font-family: fantasy;  font-size: 30em;  font-weight: bold; }//scss.funky {  font: 20px/24px {    family: fantasy;    weight: bold;  }}//css.funky {  font: 20px/24px;    font-family: fantasy;    font-weight: bold; }

5.注释

Sass 支持标准的 CSS 多行注释 /* */,以及单行注释 //,前者会 被完整输出到编译后的 CSS 文件中,而后者则不会。
//scss/* This comment is * several lines long. * since it uses the CSS comment syntax, * it will appear in the CSS output. */body { color: black; }// These comments are only one line long each.// They won't appear in the CSS output,// since they use the single-line comment syntax.a { color: green; }//css/* This comment is * several lines long. * since it uses the CSS comment syntax, * it will appear in the CSS output. */body {  color: black; }a {  color: green; }


通过 #{} 插值语句可以在选择器或属性名中使用变量:
//scss$name: foo;$attr: border;p.#{$name} {  #{$attr}-color: blue;}//cssp.foo {  border-color: blue; }
#{} 插值语句也可以在属性值中插入 SassScript,大多数情况下,这样可能还不如使用变量方便,但是使用 #{} 可以避免 Sass 运行运算表达式,直接编译 CSS。
//scssp {  $font-size: 12px;  $line-height: 30px;  font: #{$font-size}/#{$line-height};}//cssp {  font: 12px/30px; }


7.@debug

通过@debug进行scss的degubber阻断
//scss@debug 10em + 12em;//cssLine 1 DEBUG: 22em















原创粉丝点击