「ドットインストール Sass入門」をざっくり一周した
メモ。
学んだこと
1 Sassとはなにか?
CSSを効率的に書くための記法
2つの記法がある
今はscssの方が主流
2 はじめてのSass
// scssは子要素のスタイル指定を以下のように入れ子で書ける #main { width: 90%; p { // -> #main p font-size: 14px; } }
3 自動で変換させてみよう
# 変更があった場合、自動で変換を走らせる sass --watch (監視ディレクトリ):(変換先ディレクトリ)
4 入れ子構造を使ってみよう
// 疑似要素の書き方の例 // '&'は親要素を表すセレクタ a { &:hover { // -> a:hover font-weight: bold; } }
5 変数を使ってみよう
// '$'で変数宣言ができる('='ではなく、cssと同じように':'で宣言) $baseFontSize: 14px; p { font-size: $baseFontSize; // -> 14px .sub { // 計算も行える font-size: $baseFontSize - 2px; // -> 12px } }
6 文字列を扱ってみよう
// 文字列は""で囲う $imgDir: "../img/"; #main { // 文字列結合は'+'でできる background: url($imgDir + "bg.png"); // -> ../img/bg.png // 文字列内で変数展開する場合は'#{変数}'とする background: url("#{$imgDir}mg.png"); // -> ../img/bg.png p { // '{}'内は評価せよという意味合いなので、計算も行える font-size: #{12 + 12}px; // -> 14px } }
7 色を扱ってみよう
// CSSで解釈できる記法で色を指定できる $brandColor: red; p { // 指定した分明るくする color: lighten($brandColor, 30%) }
lighten()
などの、ビルトイン関数はModule: Sass::Script::Functionsで確認できる
8 @if文を使ってみよう
$debugMode: true; // scssでの条件分岐 #main { @if $debugMode { color: red; } @else { color: green; } }
9 @for,@while文を使ってみよう
// scssでのforループ @for $i from 10 through 14 { .fs#{$i} { font-size: #{$i}px; } } // scssでのwhileループ $i: 10; @while $ i <= 14 { .fs#{$i} { font-size: #{$i}px; } $i: $i + 1; }
10 リストを扱ってみよう
// リストはカンマ区切りで宣言 $animals: cat, dog, tiger; @each $animal in $animals { .#{$animal}-icon { background: url("#{$animal}.png"); } }
11 関数を使ってみよう(1)
12 関数を使ってみよう(2)
$totalWidth: 940px; $columnCount: 5; // scssでの関数作成の例 // 横幅とカラム数から、カラム1つ分の横幅を計算 @function getColumnWidth($width, $count) { $padding: 10px; $columnWidth: floor($width - ($padding * ($count - 1)) / $count); // 変換時にコンソールに値を出力する @debug $columnWidth; @return $columnWidth; } .grid { float: left; width: getColumnWidth($totalWidth, $columnCount); }
13 ファイルを分離させてみよう
分割したファイルは'_‘で始まるファイル名にする
// "_settings.scss"を読み込む @import "settings"; // "_functions.scss"を読み込む @import "functions";
14 @mixinを使ってみよう
@mixin
で定義したコード片が、@include
で挿入した箇所で展開される
// 引数や、デフォルト値をつけることもできる @mixin round($radius: 4px) { border-radius: $radius; // 引数がなかった場合、4px } .label { font-size: 12px; @include round(5px); // -> border-radius: 5px; }
15 @extendを使ってみよう
スタイルの継承
// 返還前のscssファイル .msg { font-size: 12px; font-weight: bold; padding: 2px 4px; background: red; color: white; } .errorMsg { @extend: msg; background: red; } .warningMsg { @extend: msg; background: orange; }
これがCSSになると以下のようになる
// 変換後のcssファイル .msg .errorMsg .warningMsg { font-size: 12px; font-weight: bold; padding: 2px 4px; background: red; color: white; } .errorMsg { background: red; } .warningMsg { background: orange; }
共通するプロパティは一つのルールセットに、差分だけが新たなルールセットに、と合理的なコードとして生成される。