0
点赞
收藏
分享

微信扫一扫

Sass 条件语句、循环语句、自定义函数

前言

本文主要记录了Sass 条件语句、循环语句、自定义函数的基本用法。

条件语句

在Sass中可以使用@if@if-else@if-else 来进行条件判断,用法和JS相同。

    $width: 200px;
    p {
      @if ($width == 200px) {
        color: #cc6699;
      } @else if ($width == 300px) {
        color: #f97c00;
      } @else {
        color: #eb1c27;
      }
    }

编译为

    p {
      color: #cc6699;
    }
    /*# sourceMappingURL=demo.css.map */

循环语句

在Sass中可以使用@for@while@each 来进行循环操作。

@for

@for的用法不同于JS,Sass中的for有两种格式:

@for $i from n through m

  • @for $i from n through m 表示变量i 的范围是[n, m],包含m
    @for $i from 1 through 3 {
      .item-#{$i} { width: 200px + $i*10; }
    }

编译为

    .item-1 {
      width: 210px;
    }

    .item-2 {
      width: 220px;
    }

    .item-3 {
      width: 230px;
    }
    /*# sourceMappingURL=demo.css.map */

@for $i from n to m

  • @for $i from n to m 表示变量i 的范围是[n, m),不包含m
    @for $i from 1 to 3 {
      .item-#{$i} { width: 200px + $i*10; }
    }

编译为

    .item-1 {
      width: 210px;
    }

    .item-2 {
      width: 220px;
    }
    /*# sourceMappingURL=demo.css.map */

@while

与其他控制指令一样, @while 指令直到语句计算结果为false,它迭代地输出嵌套样式。 要注意的关键是,计数器变量需要在每次迭代时递增/递减。

在这里插入图片描述

@each

在@each中,定义一个变量,其中包含列表中每个项目的值。

@each用法:

@each $var in <list or map>

示例:

在这里插入图片描述

自定义函数

Sass 支持自定义函数,在Sass中可以使用 @function编写函数。

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

    @function grid-width($n) {
      @return $n * $grid-width + $gutter-width;
    }

    #sidebar { width: grid-width(3); }

编译为

    #sidebar {
      width: 130px;
    }
    /*# sourceMappingURL=demo.css.map */

可以传递若干个全局变量给函数作为参数。

ps: 建议在自定义函数前添加前缀避免命名冲突

本文到此结束

如果大家还有什么其他想法,欢迎在评论区交流!

举报

相关推荐

0 条评论