Sassのforループと変数を使うと、marginやpadding、フォントサイズなど一定の倍数で数値が変化するCSSを簡単に大量生産できる。
目次
forループの使い方
書き方にはthrough
とto
の2つがある。through
は終わりの値を含み、to
は含まない。
・@for $変数名 from 開始値 through 終了値 {処理}
.scss(through)
@for$変数名from1through10{処理}
$i
は1〜10まで。
・@for $変数名 from 開始値 to 終了値 {処理}
.scss(to)
@for$変数名from1to10{処理}
$i
は1〜9まで。
変数の呼び出し方法
変数の呼び出し方法は状況により2つある。
- 変数の値をCSSのプロパティの値として使用する。(あるいは四則演算で使う)
- 変数の値をセレクタや処理の途中で使う。
1. 変数の値をCSSのプロパティの値として使用する
▼値をそのまま使用
.scss
$slite-dark:#333;.defalut-text{color:$slite-dark}
↓CSSにコンパイル
.css
.defalut-text{color:#333;}
▼四則演算
.scss
$oct:8;.small-text{font-size:$oct/2;}.large-test{font-size:$oct*4;}
↓CSSにコンパイル
.css
.small-text{font-size:4;}.large-test{font-size:32;}
2. 変数の値をセレクタや処理の途中で使う
定義した変数をセレクタや処理一部で呼び出すには#{ }
の中で$変数名
を使う。
.scss
$tri:3;h#{$tri}{font-size:#{$tri*6}px;}
↓CSSにコンパイル
.css
h3{font-size:18px;}
marginを持ったプロパティの一括生成
forと変数を組み合わせてmarginのパターンを生成する。
例として8pxの倍数で8px~40pxまでmarginを設定してみる。(命名規則はFLOCSSを採用)
▼sassの記述
.scss
@for$ifrom0through5{//margin.u-mt-#{$i}{margin-top:#{$i*8}px!important;}.u-mb-#{$i}{margin-bottom:#{$i*8}px!important;}.u-ml-#{$i}{margin-left:#{$i*8}px!important;}.u-mr-#{$i}{margin-right:#{$i*8}px!important;}.u-m-#{$i}{margin:#{$i*8}px!important;}}
u-mt
はutilityレイヤーのMergin Topの略。- モジュールに追加するプロパティになるので強制適用の
!important
を設定。
↓CSSにコンパイル
▼コンパイル後のコード
.css
.u-mt-0{margin-top:0px!important;}.u-mb-0{margin-bottom:0px!important;}.u-ml-0{margin-left:0px!important;}.u-mr-0{margin-right:0px!important;}.u-m-0{margin:0px!important;}.u-mt-1{margin-top:8px!important;}.u-mb-1{margin-bottom:8px!important;}.u-ml-1{margin-left:8px!important;}.u-mr-1{margin-right:8px!important;}.u-m-1{margin:8px!important;}.u-mt-2{margin-top:16px!important;}.u-mb-2{margin-bottom:16px!important;}.u-ml-2{margin-left:16px!important;}.u-mr-2{margin-right:16px!important;}.u-m-2{margin:16px!important;}.u-mt-3{margin-top:24px!important;}.u-mb-3{margin-bottom:24px!important;}.u-ml-3{margin-left:24px!important;}.u-mr-3{margin-right:24px!important;}.u-m-3{margin:24px!important;}.u-mt-4{margin-top:32px!important;}.u-mb-4{margin-bottom:32px!important;}.u-ml-4{margin-left:32px!important;}.u-mr-4{margin-right:32px!important;}.u-m-4{margin:32px!important;}.u-mt-5{margin-top:40px!important;}.u-mb-5{margin-bottom:40px!important;}.u-ml-5{margin-left:40px!important;}.u-mr-5{margin-right:40px!important;}.u-m-5{margin:40px!important;}
コンパイルすると一瞬で大量のコードが生成される。
htmlへの適用例
htmlへの適用は簡単。例えばクラス属性にu-mt-3
を指定すれば、margin-top:24px
が適用される。
<divclass="u-mt-3">テスト</div>
paddingを持ったプロパティの一括生成
paddingも同様にすれば一瞬で大量生成できる。
.scss
@for$ifrom0through10{.u-pt-#{$i}{padding-top:#{$i*8}px!important;}.u-pb-#{$i}{padding-bottom:#{$i*8}px!important;}.u-pl-#{$i}{padding-left:#{$i*8}px!important;}.u-pr-#{$i}{padding-right:#{$i*8}px!important;}.u-p-#{$i}{padding:#{$i*8}px!important;}}
変数を0〜10にすれば、0〜80pxまで作成できる。
(コンパイル結果は膨大なので割愛)
font-sizeを持ったプロパティの一括生成
font-sizeも同様にすれば一瞬で大量生成できる。
.scss
@for$ifrom1through20{.u-fs-#{$i}{padding-top:#{$i*4}px;}
4px ~ 20px(4px毎)まで生成できる。
forループと変数は他にも何かと応用可能。