0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Sassでfor文を使ってみる

Posted at

はじめに

CSSを書いていると、同じようなスタイルを繰り返し書くことがあります。
Sass(.scss)では、for文を使って繰り返し処理を行い、スタイルを効率的に生成できます。
この記事では、基本的なfor文の書き方から、実践的な活用方法、そしてちょっとしたTipsまで紹介します。


for文を書いてみる

Sassのfor文は以下のような構文で書きます。

style.scss
@for $i from 1 through 5 {
  .box-#{$i} {
    width: 100px * $i;
  }
}

出力されるCSS

style.css
.box-1 {
  width: 100px;
}
.box-2 {
  width: 200px;
}
.box-3 {
  width: 300px;
}
.box-4 {
  width: 400px;
}
.box-5 {
  width: 500px;
}

through と to の違い

  • hrough : 終了値を含む(1 through 5 → 1〜5まで)
  • to : 終了値を含まない(1 to 5 → 1〜4まで)

実践的なfor文の使い方

グリッドレイアウトのクラスを自動生成

style.scss
.container {
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
}

@for $i from 1 through 12 {
  .col-#{$i} {
    grid-column: span 1;
  }
}
index.html
<div class="container">
  <div class="col-1"></div>
  <div class="col-2"></div>
  <div class="col-3"></div>
  <div class="col-4"></div>
  <div class="col-5"></div>
  <div class="col-6"></div>
  <div class="col-7"></div>
  <div class="col-8"></div>
  <div class="col-9"></div>
  <div class="col-10"></div>
  <div class="col-11"></div>
  <div class="col-12"></div>
</div>

image.png

12分割のgridレイアウトができました。

アニメーションのディレイを自動付与

style.scss
@for $i from 1 through 5 {
  .fadein-#{$i} {
    animation-delay: 0.2s * $i;
  }
}

これで、要素ごとに順番でフェードインさせる演出が簡単に作れます。

ネストとの組み合わせ

style.scss
.list {
  @for $i from 1 through 3 {
    li:nth-child(#{$i}) {
      color: hsl(200, 50%, 20% * $i);
    }
  }
}

最後に

Sassのfor文を使うと、重複コードを減らし、保守性の高いスタイルを実現できます。
グリッドやアニメーションのようなパターン生成に特に有効です。

もしまだ使ったことがない方は、ぜひ小さなプロジェクトから試してみてください。
Sassのループは、CSSを書く効率を大きく変えてくれます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?