丸子学SASS(学习1小时 - 控制指令)

2023-12-17  本文已影响0人  丸子小姐__不懂爱

控制指令

if() 条件

当@if的表达式返回值不是 false 或者 null时,条件成立,输出括号内的代码

p {
  @if 1 + 1 == 2 { border: 1px solid; }
  @if 5 < 3 { border: 2px dotted; }
  @if null  { border: 3px double; }
}

@if,声明后可以跟多个 @else if声明

$type: monster;
p {
  @if $type == ocean {
    color: blue;
  } @else if $type == matador {
    color: red;
  } @else if $type == monster {
    color: green;
  } @else {
    color: black;
  }
}

@for 循环值

@for 指令可以在限制的范围内重复输出格式,每次按要求(变量的值)对输出结果做出变动。这个指令包含两种格式:@for var from <start> through <end>,或者 @forvar from <start> to <end>,区别在于 through 与 to 的含义:当使用 through 时,条件范围包含 <start> 与 <end> 的值,而使用 to 时条件范围只包含 <start> 的值不包含 <end> 的值。另外,var 可以是任何变量,比如i;<start> 和 <end> 必须是整数值。

@for $i from 1 to 3 {
  .item-#{$i} { width: 2em * $i; }
}

@each 循环列表

@each 指令的格式是 var in <list>,var 可以是任何变量名,比如 length 或者name,而 <list> 是一连串的值,也就是值列表

@each $animal in puma, sea-slug, egret, salamander {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
  }
}

@each可以通过设置多重变量来进行循环多个列表

@each $animal, $color, $cursor in (puma, black, default),
                                  (sea-slug, blue, pointer),
                                  (egret, white, move) {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
    border: 2px solid $color;
    cursor: $cursor;
  }
}

@while 循环

@while 指令重复输出格式直到表达式返回结果为 false。这样可以实现比 @for 更复杂的循环

$i: 6;
@while $i > 0 {
  .item-#{$i} { width: 2em * $i; }
  $i: $i - 2;
}

混合指令

混合指令(Mixin)用于定义可重复使用的样式,避免了使用无语意的 class,比如 .float-left。混合指令可以包含所有的 CSS 规则,绝大部分 Sass 规则,甚至通过参数功能引入变量,输出多样化的样式

定义混合指令

@mixin large-text {
  font: {
    family: Arial;
    size: 20px;
    weight: bold;
  }
  color: #ff0000;
}

引用混合样式@include

.page-title {
  @include large-text;
  padding: 4px;
  margin-top: 10px;
}

参数

参数用于给混合指令中的样式设定变量,并且赋值使用。在定义混合指令的时候,按照变量的格式,通过逗号分隔,将参数写进圆括号里。引用指令时,按照参数的顺序,再将所赋的值对应写进括号

@mixin sexy-border($color, $width) {
  border: {
    color: $color;
    width: $width;
    style: dashed;
  }
}
p { @include sexy-border(blue, 1in); }

参数可以设置默认值 ,如下

@mixin sexy-border($color, $width: 1in)

在引用时可以设置关键词 如下

@include sexy-border($color: blue, $width: 2in)

当不能确定指令需要使用多少个参数时,可以设置参数变量 如下

@mixin box-shadow($shadows...)

引用混合指令时,同样可以使用参数变量 如下

$values: #ff0000, #00ff00, #0000ff;
.primary {
  @include colors($values...);
}

混合指令同样可以实现参数的传递 如下

@mixin wrapped-stylish-mixin($args...) {
  font-weight: bold;
  @include stylish-mixin($args...);
}
.stylish {
  @include wrapped-stylish-mixin(#00ff00, $width: 100px);
}

向混合样式中导入内容

在引用混合样式的时候,可以先将一段代码导入到混合指令中,然后再输出混合样式,额外导入的部分将出现在 @content 标志的地方

@mixin apply-to-ie6-only {
  * html {
    @content;
  }
}
@include apply-to-ie6-only {
  #logo {
    background-image: url(/logo.gif);
  }
}

函数指令

基本用法

$grid-width: 40px;
$gutter-width: 10px;

@function grid-width($n) {
  @return $n * $grid-width + ($n - 1) * $gutter-width;
}
#sidebar { width: grid-width(5); }

函数一样可以使用 关键词参数和默认参数

上一篇 下一篇

猜你喜欢

热点阅读