-1

我设法用纯 CSS 编写 FizzBu​​zz 作为个人 Hello World 来学习如何编写样式表。我想对 Sass 做同样的事情,但我不确定如何利用 Sass 语法或语义来改进这一点。

目前,我有一个共同呈现 FizzBu​​zz 的 .html 文件和 .scss 文件,但 .scss 文件仍然是纯 CSS 代码。如何通过使用 Sass 扩展使其更简洁或更具表现力?

例子:

body { counter-reset: i; }

div { counter-increment: i; }
div:after { content: "" counter(i); }

div:nth-child(3n) { visibility: hidden; }
div:nth-child(3n):after { visibility: visible; content: "Fizz"; }

div:nth-child(5n) { visibility: hidden; }
div:nth-child(5n):after { visibility: visible; content: "Buzz"; }

div:nth-child(15n) { visibility: hidden; }
div:nth-child(15n):after { visibility: visible; content: "FizzBuzz"; }

资源:

https://github.com/mcandre/mcandre/tree/master/sass

4

2 回答 2

0

Most people start with the nesting, so you might have something like (Scss syntax, btw):

div {
  counter-increment: i;

  &:nth-child(3n) {
    visibility: hidden;

    &:after {
      visibility: visible;
      content: "Fizz";
    }
  }
// Repeat for remainder :nth-child declarations
}

The & symbol means it's still the "parent" element (ie - &:nth-child(3n) = div:nth-child(3n)).

This particular example doesn't provide a lot of room for turning it into Sass and displaying a lot of the benefit of doing so. Some of the power of Sass resides in things like variables and mixins (one of the big uses is dealing with vendor prefixes and being able to split the source into different files and having it all compile to one and minified).

于 2013-08-02T19:33:24.353 回答
0

另一种可能性(正如 Shauna 提到的)是使用@while带有 a 的循环@mixin来自动化事情:

SCSS

@mixin fizzBuzz($count) {
    @if $count % 5 == 0  and $count % 3 == 0 {
      @extend .buzzDiv;
      &:after {
       content: "FizzBuzz";
      }
    }
    @else if $count % 3 == 0 {
      @extend .buzzDiv;
      &:after {
        content: "Fizz";
      }
    }
    @else if $count % 5 == 0 {
      @extend .buzzDiv;
      &:after {
        content: "Buzz";
      }
    }
    @else {
      &:after {
        content:"#{$counter}"
      }
    }
}

// reduce our css bloat
.buzzDiv {
  visibility: hidden;
  &:after {
    visibility:visible;
  }
}


$counter: 1;

@while $counter <= 100 {
  div.no#{$counter} {
    @include fizzBuzz($counter)
  }
  $counter: $counter + 1;
}

密码笔

可能有更优雅的方式来编写控制结构(我仍然在这里重复自己一点),但是这种方法可以让您在“缩放”时节省一些击键。

有关 SASS 控制指令的更多信息,请点击此处

于 2013-08-02T21:24:40.077 回答