現在、SCSSというファイルを現在のシステムのデザインに載せ替える作業を進めている。
そこで出てきた SCSS 。
拡張子を見たことはあったが、扱うことになるとは、、、、
そのために簡単にでもどのように動作しているかを確認することにした。
SCSS とは
CSS を拡張した記法。
Sass の書き方の一種。
変数・ネスト・mixin・関数・モジュールの便利さを足して、最終的に CSS にコンパイルして利用する。
SCSS記法の他にはSass記法がある。
これは波括弧やセミコロンが省略できる。
$main-color: #3498db
body
background: $main-color
font-size: 16px
⸻
まずはインストール(Dart Sass)
npm i -D sass
# 単発コンパイル
npx sass src/styles.scss public/styles.css
コンパイルはVite/Webpack などのビルドツールが、その「変換」を自動でやってくれるらしい。
⸻
変数($var)
$brand: #3b82f6;
$space: 8px;
.button {
background: $brand;
padding: $space * 2; // 16px
}
変数を利用することができる。
色や余白を管理できる。
⸻
ネスト(入れ子)+ 親参照(&)
.card { //<div class="card"> と書いた要素に適用
padding: 1rem;
h2 { margin: 0; } //.card の中にある <h2> タグ にスタイルを当てる
.cta { //.card の中にある .cta クラス要素に適用
text-decoration: underline;
&:hover { opacity: .8; }
}
}
HTMLの入れ子構造に沿って書ける。
&:hoverについて
本来はこう書く
.cta:hover {
text-decoration: underline;
opacity: .8;
}
⸻
@mixin と @include
@mixin btn($radius: .5rem) {
display: inline-flex;
gap: .5rem;
padding: .5rem 1rem;
border-radius: $radius;
}
.button { @include btn(1rem); }
よく使うスタイルをまとめておける。
$radiusは初期が.5rem。
利用するときにbtn()で引数を指定すると$radiusが1remに置き換わる。
⸻
関数(@function)
@function pxToRem($px, $base: 16) {
@return ($px / $base) * 1rem;
}
.title { font-size: pxToRem(20); } // 1.25rem
値を返す関数で計算や書式化ができる。
⸻
継承(@extend とプレースホルダ %)
%button-base {
display: inline-flex;
align-items: center;
}
.btn {
@extend %button-base;
padding: .5rem 1rem;
}
既存セレクタのスタイルを継承。
@mixin と似ているが、% (placeholder) は引数が利用できない。
また、参照するだけなのでCSSが若干軽くなる。
@mixin は呼び出すたびにコピペしているように展開されるみたい。
完全に同じスタイルを共有する要素 は % (placeholder)
パラメータ付きで変化するもの(例:角丸のサイズ違いのボタン、テーマカラー違いの見出し) は**@mixin**
⸻
モジュール化(@use / @forward)
分割: _variables.scss(先頭_は直接出力しないパーシャル = 単体ではコンパイル対象にならない。)
// _variables.scss
$brand: #3b82f6;
$space: 8px;
使う側:
// main.scss
@use './variables';
h1 { color: variables.$brand; }
公開集約:
// index.scss(ライブラリ側で公開面をまとめる)
@forward './variables';
@forward は他のパーシャル(分割ファイル)を一つにまとめるときに使える。
// _colors.scss
$main-color: #3498db;
// _typography.scss
$font-size-base: 16px;
// _index.scss
@forward 'colors';
@forward 'typography';
// styles.scss
@use 'index';
body{
color: index.$main-color;
font-size: index.$font-size-base;
}
⸻
ビルトインモジュール例(sass:color)
@use 'sass:color';
$brand: #3b82f6;
.button {
background: color.scale($brand, $lightness: -10%); // 色を10%暗く
}
JSの標準ライブラリみたいなもん。
⸻
文字列補間(#{})
$size: 24;
.icon-#{$size} { width: #{$size}px; height: #{$size}px; }
変数からクラス名・値を組み立てられる。