Skip to content

Sass チートシート

変数、ネスト、mixin を備えた強力な CSS プリプロセッサ。

01

Sass の基本

変数とネスト

$ 接頭辞を使うのが、Sass の変数です。HTML の構造を映し返すのが、ネストです。親のセレクタを参照するのが、& です。色の操作には、lighten()/darken() を使いましょう。

sass
// SCSS syntax ($var)
$primary-color: #3498db;
$font-stack: -apple-system, sans-serif;

body {
  font-family: $font-stack;
  color: $primary-color;

  a {
    color: lighten($primary-color, 20%);

    &:hover {
      color: darken($primary-color, 10%);
    }
  }
}

SCSS 対インデント構文

CSS のスーパーセットであるのが、SCSS(.scss)です。すべての有効な CSS ファイルが、有効な SCSS です。波括弧とセミコロンを取り除き、インデントに頼るのが、Sass(.sass)です。より人気があり移行しやすいのが、SCSS です。1 つを選び、プロジェクト内で一貫させましょう。

sass
// SCSS (.scss) - uses braces and semicolons
.box {
  width: 100px;
  height: 100px;
}

// Sass (.sass) - indentation-based, no braces/semicolons
.box
  width: 100px
  height: 100px

// Both compile to the same CSS
// .box { width: 100px; height: 100px; }

コメント

出力で取り除かれるのが(サイレントな)、// のコメントです。コンパイル済み CSS で保たれるのが、/* */ のコメントです。圧縮/本番モードでもさえ保たれるのが(ライセンスか重要なお知らせに)、/*! */ のコメントです。内部のドキュメントには、// を。

sass
// Single-line comment - NOT compiled to CSS
/* Multi-line comment - compiled to CSS */
/*! Important comment - always kept even in compressed mode */

// Silent comment for developers
$base-font: 16px;

/*! Keep this copyright notice */
body { font-size: $base-font; }

コンパイル

.scss/.sass を .css へコンパイルするのが、Sass です。保存時の自動再コンパイルが、--watch です。出力のスタイル:expanded(デフォルトで読みやすい)、nested(インデント付き)、compact(1 行に 1 ルール)、compressed(本番向けに minify)です。ファイルサイズを減らすため、本番では compressed を。

sass
// Compile a single file
// $ sass input.scss output.css

// Watch for changes
// $ sass --watch input.scss:output.css

// Watch a directory
// $ sass --watch scss/:css/

// Compressed output
// $ sass --style=compressed input.scss output.css

// Four output styles: expanded, nested, compact, compressed
$width: 100px;
.box { width: $width; }

セレクタ継承の概観

変数、ネスト、mixin、継承、関数、制御フローを加える CSS プリプロセッサが、Sass です。これらが、繰り返し(DRY 原則)を減らし、大きなスタイルシートを管理可能にします。標準の CSS へコンパイルダウンされるのが、すべての Sass の機能です。

sass
// Sass adds programming features to CSS:
// 1. Variables ($var)
// 2. Nesting
// 3. Mixins (@mixin / @include)
// 4. Inheritance (@extend)
// 5. Functions (@function)
// 6. Control directives (@if, @for, @each, @while)
// 7. Partials & Modules (@use, @forward)

// These features help keep stylesheets DRY and maintainable.
$radius: 4px;
.card { border-radius: $radius; }
02

変数とデータ型

変数の宣言とスコープ

グローバルであるのが、任意のブロックの外で宣言された変数です。そのブロックのローカルであるのが、ブロックの内側で宣言された変数です。同名のグローバルを覆い隠すのが、ローカルです。グローバル名前空間を汚染しないために、ローカルを使いましょう。

sass
$color: #333;          // global scope
$padding: 10px;         // global

.block {
  $local-color: #fff;   // local to .block
  color: $local-color;
  padding: $padding;    // can read globals
}

// $local-color is NOT available here
// .other { color: $local-color; } // ERROR

!default フラグ

変数が null か未定義のときにだけ、値を割り当てるのが、!default です。これにより、ライブラリをインポートする「前に」変数を設定することで、ユーザーがライブラリのデフォルトを上書きできます。設定可能な Sass のライブラリとデザインシステムの構築には、決定的に重要です。

sass
// Only assign if the variable is not already defined
$base-color: #333 !default;
$base-color: #fff; // this wins (already? no - assigned above first)

// Useful in libraries/partials for user overrides
// _theme.scss
$primary: blue !default;
.button { background: $primary; }

// User config BEFORE importing
// $primary: red;
// @use 'theme';  -> button is red

!global フラグ

ブロック(mixin、関数、制御ディレクティブ)の内側から、明示的にグローバルのスコープへ割り当てるのが、!global です。デフォルトでローカルであるのが、Sass 3 以降の、ブロック内の代入です。控えめに !global を使いましょう — グローバルな変更が、コードを推論し難くします。

sass
$count: 0;

@for $i from 1 through 3 {
  $count: $count + $i !global;
}

// $count is now 6 (1+2+3)
.total { content: "#{$count}"; }

// Without !global, the assignment inside @for
// would create a local variable instead

データ型

7 つのデータ型を持つのが、Sass です:数値(単位付き)、文字列、色、真偽値、null、リスト、マップです。文字列として型を返すのが、type-of() です。関数と制御ディレクティブを正しく使うためには、型の理解が不可欠です。

sass
// Sass has 7 data types:
$number:  16px;              // number (with optional unit)
$string:  "Helvetica";       // string (quoted or unquoted)
$color:   #3498db;           // color
$boolean: true;              // boolean (true/false)
$null:    null;              // null (no value)
$list:    10px 20px 30px;    // list (space or comma separated)
$map:     (key: value);      // map (key-value pairs)

// Type checking
type-of($number)  // number
type-of($list)    // list
type-of($map)     // map

補間 #{}

セレクタ、プロパティ名、文字列、そして、素の変数が許されないその他の場所へ、変数を注入するのが、#{} の補間です。値の中でしか機能しない $var と違い、ほとんどどこでも機能するのが、#{} です。任意の値を文字列表現へ変換します。

sass
$name: "user";
$version: 2;

// Use #{} to insert variables into selectors and strings
.#{$name}-avatar { background: url("/img/#{$name}.png"); }

// In property names and values
.icon-#{$name} {
  content: "v#{$version}";
}

// Interpolation in @media and @include
@media (max-width: #{$version * 100}px) {
  body { font-size: 14px; }
}
03

ネスト

基本のネスト

HTML の階層を映し返すセレクタを書け、親セレクタの繰り返しを避けられるのが、ネストです。子孫のセレクタを作るのが、コンパイル済み CSS です。これが読みやすさを改善しますが、乱用が過度に具体的なセレクタを作るため — ネストは最大 3〜4 レベルに保ちましょう。

sass
// SCSS nesting mirrors HTML structure
.nav {
  background: #333;

  ul {
    list-style: none;
    margin: 0;

    li {
      display: inline-block;
    }
  }

  a {
    color: white;
    text-decoration: none;
  }
}

// Compiles to: .nav {...} .nav ul {...} .nav ul li {...} .nav a {...}

深いネスト(アンチパターン)

長く過度に具体的なセレクタを作るのが、深いネストです。上書きが難しく、ブラウザのマッチングが遅くなります。経験則:3〜4 レベルより深くネストしないこと。保守性のために、明示的な BEM スタイルのクラスで、深い構造を平坦化しましょう。

sass
// AVOID: overly deep nesting
.header {
  .nav {
    > ul {
      li {
        a {
          span {  // 5 levels deep!
            color: red;
          }
        }
      }
    }
  }
}

// Compiles to: .header .nav > ul li a span
// Too specific - hard to override, slow to match

// BETTER: flatten with classes
.header-nav-link-text { color: red; }

ネストしたプロパティ

関連するサブプロパティをグループ化するのが、(font:、border:、margin: などの)プロパティの名前空間の後のコロンによる、ネストしたプロパティです。接頭辞の繰り返しを避けられ、純粋に構文糖衣です。font-family、border-top などの標準の CSS プロパティへコンパイルされます。

sass
.icon {
  // Shorthand for font-family, font-size, font-weight...
  font: {
    family: "Arial";
    size: 14px;
    weight: bold;
  }

  // border-top, border-right, etc.
  border: {
    top: 1px solid #ccc;
    bottom: 2px dashed #999;
  }
}

// Compiles to: font-family, font-size, font-weight, border-top, border-bottom

メディアクエリのネスト

ルールの内側に @media クエリをネストすれば、レスポンシブなスタイルがコンポーネントと同じ場所に置かれ、保守性が改善します。@media をトップレベルへ持ち上げるのが、コンパイル済み CSS です。メディアクエリをファイルに散らすより、これは読みやすさの大きな勝ちです。

sass
.container {
  width: 100%;

  // Media query nested inside the rule
  @media (min-width: 768px) {
    width: 720px;
  }

  @media (min-width: 1024px) {
    width: 960px;
  }
}

// Compiles to:
// .container { width: 100%; }
// @media (min-width: 768px) { .container { width: 720px; } }
// @media (min-width: 1024px) { .container { width: 960px; } }

ネストでのセレクタのリスト

カンマ区切りのセレクタのリストをネストすると、Sass が各アイテムを親と組み合わせます。各組み合わせを手で書くより、これがきれいです。複数の親へ一度にクラス/修飾子を追記するため、& もネストしたリスト内で使えます。

sass
.btn {
  // Comma creates a selector list
  .icon,
  .label {
    color: white;
  }
}

// Compiles to:
// .btn .icon, .btn .label { color: white; }

// Nesting a list with &
.card,
.panel {
  &.active { border-color: blue; }
}

// .card.active, .panel.active { border-color: blue; }
04

親セレクタ(&)

基本の親セレクタ

親セレクタを参照するのが、& です。疑似クラス(:hover、:focus)、疑似要素(::before)、修飾子をネストできます。関連するスタイルがまとめて保たれます。.button:hover へコンパイルされるのが、&:hover です。& がなければ、子孫セレクタになってしまいます。

sass
.button {
  background: blue;
  color: white;

  // & refers to the parent (.button)
  &:hover {
    background: darkblue;
  }

  &:focus {
    outline: 2px solid blue;
  }

  &::after {
    content: "→";
  }
}

// Compiles to: .button, .button:hover, .button:focus, .button::after

& による BEM

簡潔に BEM(Block Element Modifier)の命名を可能にするのが、& です。親へ __title を追記し、.card__title を作るのが、&__title です。修飾子クラスを作るのが、&--featured です。ブロック定義内で、BEM クラスの生成が DRY かつ一貫して保たれます。

sass
// BEM methodology with parent selector
.card {
  background: white;

  &__title {       // .card__title
    font-size: 18px;
  }

  &__body {        // .card__body
    padding: 16px;
  }

  &--featured {    // .card--featured
    border-color: gold;
  }

  &--featured &__title {  // .card--featured .card__title
    color: gold;
  }
}

親セレクタの接尾辞化

ネストしたセレクタの先頭に & を置くと、接尾辞が親へ追記され、.button-primary のような複合セレクタが生成されます。バリアントの命名に有用です。注意 — 接尾辞化の乱用が、ソースを読むときの、生成されたクラス名を不明瞭にし得ます。

sass
.button {
  background: blue;

  // Append suffix to parent
  &-primary { background: darkblue; }    // .button-primary
  &-secondary { background: gray; }      // .button-secondary
  &-danger { background: red; }          // .button-danger

  // Combining with state
  &-primary.is-active { font-weight: bold; }
}

// Generates: .button, .button-primary, .button-secondary, .button-danger

逆のネスト

ネストしたセレクタの末尾に & を置くと、順序が逆になり — 親が子孫になります。コンポーネントが祖先のコンテキストへ適応する、.dark-theme .modal のような、文脈/テーマのスタイルに完璧です。コンテキスト固有の上書きを、コンポーネントの近くに保ちます。

sass
.modal {
  // & at the end - parent as descendant
  .dark-theme & {
    background: #222;
    color: #eee;
  }

  .sidebar & {
    width: 200px;
  }
}

// Compiles to:
// .dark-theme .modal { background: #222; color: #eee; }
// .sidebar .modal { width: 200px; }

// Useful when parent is styled differently in a context

1 セレクタ内の複数の &

単一のセレクタ内で、& を複数回使えます。兄弟のスタイリングのための .button + .button を生成するのが、& + & です。繰り返される要素の間のスペーシングや、複雑な状態ベースのセレクタに強力です。完全な親セレクタに置き換えられるのが、各 & です。

sass
.button {
  // Multiple & references in one selector
  & + & {              // .button + .button (adjacent sibling)
    margin-left: 8px;
  }

  & ~ & {              // .button ~ .button (general sibling)
    margin-top: 4px;
  }

  &.active &__icon {   // .button.active .button__icon
    color: white;
  }

  .parent &.is-open &__content {
    display: block;
  }
}
05

Partials(_partial ファイル)

Partial の作成

先頭のアンダースコア付きで名付けられた Sass ファイル(例:_variables.scss)であるのが、partials です。別の CSS ファイルへコンパイルされないよう、Sass に伝えるのが、アンダースコアです。メインファイルへインポートされることを意図しているのが、partials です。コードが保守性のためモジュール化されます。

sass
// _variables.scss - partial file (underscore prefix)
$primary: #3498db;
$secondary: #2ecc71;
$font-base: 16px;

// _buttons.scss
.button {
  background: $primary;
  padding: $font-base / 2;
}

// Partials are NOT compiled to their own CSS file.
// The underscore tells Sass this is a partial.
// Import them into a main file:
// main.scss:  @use 'variables'; @use 'buttons';

Partial の命名の慣例

先頭のアンダースコア付きの、記述的な名前を使うのが、partials です。アンダースコアと拡張子を省くのが、@use や @import のステートメントです。Sass が、「variables」を _variables.scss へ自動解決します。チームがコードを素早く見つけるのを助けるのが、一貫した命名です。

sass
// Common partial naming patterns:
// _variables.scss   - variables
// _mixins.scss      - mixins
// _functions.scss   - functions
// _reset.scss       - CSS reset
// _base.scss        - base styles
// _typography.scss  - typography
// _buttons.scss     - button component
// _header.scss      - header component
// _footer.scss      - footer component
// _mediaqueries.scss - media queries

// Import without the underscore or extension:
// @use 'variables';
// @use 'mixins';

7-1 アーキテクチャのパターン

広く採用された Sass アーキテクチャが、7-1 パターンです:7 つのフォルダ(abstracts、base、components、layout、pages、themes、vendors)に加え、1 つの main.scss の入口です。関心を分離することで、大きなプロジェクトで良くスケールします。main.scss へインポートされる partials を、各フォルダが保持します。

sass
// 7-1 architecture: 7 folders, 1 main file
// sass/
//   abstracts/   - variables, functions, mixins
//   base/        - reset, typography, base styles
//   components/  - buttons, cards, nav
//   layout/      - header, footer, grid
//   pages/       - home, about specific styles
//   themes/      - theme definitions
//   vendors/     - third-party
//   main.scss    - imports everything

// main.scss
// @use 'abstracts/variables';
// @use 'base/reset';
// @use 'components/buttons';
// @use 'layout/header';

Index の partial(_index.scss)

フォルダの公開 API として振る舞い、すべての partials を転送するのが、_index.scss(か _all.scss)の partial です。1 つの @use ステートメントで、フォルダ全体をインポートできます。新しい partial を加えたら、インデックスだけを更新します — メインのファイルは変わりません。Sass のモジュールシステムのパターンが、これです。

sass
// sass/components/_index.scss
// Forward all component partials from one entry point
@forward 'buttons';
@forward 'cards';
@forward 'nav';
@forward 'modal';

// Now in main.scss, one line imports everything:
// @use 'components';
// (resolves to components/_index.scss)

// This keeps the main file clean and lets
// you reorganize partials without touching main.scss

Partial のベストプラクティス

ベストプラクティス:partial ごとに 1 つの関心、ファイルを小さく(50〜200 行)、明示的な依存管理のための @use、循環インポートの回避です。保守性と再利用を partials が改善します。依存を明示的にするのが、(古い @import と違い)、@use のステートメントです。

sass
// 1. One concern per partial
// _buttons.scss  -> only buttons
// _forms.scss    -> only forms

// 2. Keep partials small and focused
// (50-200 lines is a good target)

// 3. Use @use (not @import) for explicit dependencies
// _card.scss
@use '../abstracts/variables' as *;
@use '../abstracts/mixins' as *;

.card {
  background: $white;
  @include card-shadow;
}

// 4. Avoid circular dependencies
06

@import と @use

@import(非推奨)

非推奨なのが、@import です。グローバル名前空間を汚染し、ファイルを複数回実行し得るうえ、プライバシーも名前空間も提供しないためです。@use と @forward への移行を Sass が推奨します。既存の @import のコードは依然機能しますが、新しいプロジェクトのために移行すべきです。

sass
// @import - the OLD way (deprecated in Sass 1.80+)
@import 'variables';
@import 'mixins';
@import 'buttons';

// Problems with @import:
// 1. Globals leak across files (no namespacing)
// 2. Each @import of the same file runs it again
// 3. No way to make members private
// 4. Extends and mixins can conflict

// Use @use instead (the modern module system)
$primary: blue;

@use の基本(名前空間付き)

モジュールを一度ロードし、名前空間(デフォルトではファイル名)経由でメンバーを公開するのが、@use です。namespace.$var か namespace.mixin-name() で、メンバーへアクセスしましょう。これが、グローバル汚染と命名の衝突を防ぎます。@use が何回現れても、1 回だけロードされるのが、各モジュールです。

sass
// _variables.scss
$primary: #3498db;
$radius: 4px;

// main.scss - @use creates a namespace (filename by default)
@use 'variables';

.button {
  // Access via namespace::member
  background: variables.$primary;
  border-radius: variables.$radius;
}

// The namespace prevents naming collisions
// and makes dependencies explicit

as 付きの @use

名前空間をより短いものへ改名するのが、「as v」です。接頭辞なしで、現在のスコープへメンバーをロードするのが、「as *」です。便利ですが衝突のリスクがあるため、控えめに使いましょう。より安全で、コードを読むとき各メンバーの出身が明確になるのが、名前付きの名前空間です。

sass
// _variables.scss
$primary: blue;
$secondary: green;

// Rename the namespace with 'as'
@use 'variables' as v;

.btn {
  background: v.$primary;
  color: v.$secondary;
}

// Or remove the namespace entirely (use with caution)
@use 'variables' as *;

.card {
  background: $primary;  // direct access, no prefix
}

// 'as *' can cause collisions - prefer named namespaces

設定付きの @use(with)

ロード時に、モジュールの !default 変数を設定するのが、「with (...)」です。@import のグローバル変数の設定パターンを置き換えます。モジュールの他の使用の前に、with 句が来なければなりません。ライブラリのテーマとデザイントークンの設定の標準的な方法が、これです。

sass
// _theme.scss
$primary: blue !default;
$radius: 4px !default;

.button {
  background: $primary;
  border-radius: $radius;
}

// main.scss - configure variables on import
@use 'theme' with (
  $primary: red,
  $radius: 8px
);

// The 'with' clause sets variables marked !default
// This is how libraries are configured by users

@use 対 @import の比較

@import から @use への移行:メンバーが名前空間化され、ファイルが 1 回ロードされ、- か _ で始まるメンバーがプライベートになります(公開されません)。依存を明示的にし、うっかりのグローバル汚染を防ぐのが、@use です。大きなコードベースの移行を自動化するのが、sass-migrator のツールです。

sass
// @import (old) - global, no namespace
@import 'variables';
.button { background: $primary; }  // global $primary

// @use (new) - namespaced, loaded once
@use 'variables';
.button { background: variables.$primary; }

// Key differences:
// @import: global scope, runs multiple times, no privacy
// @use:    namespaced, runs once, supports private (-prefix)

// _mixins.scss with a private member
@mixin -internal { /* private - not exposed */ }
@mixin public { @include -internal; }

// @use only exposes non-private (no dash prefix) members
07

Mixins(@mixin / @include)

Mixin の定義と使用

再利用可能な宣言(とルールさえ)のブロックを定義するのが、@mixin です。使用された場所へ、mixin の内容を挿入するのが、@include です。ベンダーの接頭辞、clearfix、繰り返される宣言のグループに、mixins が理想的です。@extend と違い、含められるたびに、宣言が複製されるのが、mixins です。

sass
// Define a mixin with @mixin
@mixin center {
  display: flex;
  justify-content: center;
  align-items: center;
}

@mixin card-shadow {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

// Use with @include
.hero {
  @include center;
  height: 200px;
}

.modal {
  @include center;
  @include card-shadow;
}

Mixin の引数

関数のように引数を受け付けるのが、mixins です。位置で渡すか(順序が効きます)、名前で渡しましょう(順序に依存せず、より明快です)。多くの省略可能なパラメータを持つ mixins に有用なのが、名前付き引数です。異なる値をまたいで、mixins が柔軟で再利用可能になるのが、引数です。

sass
@mixin button($bg, $color) {
  background: $bg;
  color: $color;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
}

// Pass arguments by position
.btn-primary { @include button(blue, white); }
.btn-danger { @include button(red, white); }

// Pass arguments by name (clearer, order-independent)
.btn-info { @include button($color: white, $bg: teal); }

デフォルトの引数

mixins が柔軟になるのが、デフォルトの引数値によるためです。デフォルトを使うため、呼び出し側が引数を省略できます。他をデフォルトのまま保ちつつ、特定のパラメータを上書きするには、名前付き引数を使いましょう。定義時に一度でなく、mixin が含められるたびに評価されるのが、デフォルト値です。

sass
@mixin border($width: 1px, $style: solid, $color: #ccc) {
  border: $width $style $color;
}

// Use all defaults
.box { @include border; }
// border: 1px solid #ccc;

// Override one - use named args to skip earlier ones
.card { @include border($color: blue); }
// border: 1px solid blue;

// Override by position
.banner { @include border(2px, dashed); }
// border: 2px dashed #ccc;

@content 付きの mixin

@include へ渡されたスタイルのブロックを注入するのが、@content です。メディアクエリの mixins、keyframes、ラッパーのコンテキストに、極めて強力です。呼び出しのスコープで評価されるのが、含められたブロックです。そのため、呼び出し側の変数を使えます。引数の受け渡しについては、@content のセクションを。

sass
// @content lets you pass a block of styles to a mixin
@mixin respond-to($breakpoint) {
  @media (min-width: $breakpoint) {
    @content;  // injected styles go here
  }
}

.sidebar {
  width: 100%;

  @include respond-to(768px) {
    width: 250px;  // this block replaces @content
    float: left;
  }
}

// Compiles to:
// .sidebar { width: 100%; }
// @media (min-width: 768px) { .sidebar { width: 250px; float: left; } }

可変引数(...)

2 つの目的に役立つのが、... の演算子です。mixin の定義では、余分な引数をリストへ集め(可変引数)、呼び出し場所では、リストを個々の引数へ展開します。可変個の値を受け付ける CSS のプロパティを包む mixins には(box-shadow と transition のように)、これが不可欠です。

sass
// ... captures multiple args into a list (or expands a list)
@mixin box-shadow($shadows...) {
  box-shadow: $shadows;
}

.card { @include box-shadow(0 1px 2px black, 0 4px 8px gray); }
// box-shadow: 0 1px 2px black, 0 4px 8px gray;

// Expanding a list into arguments
$shadows: 0 1px 2px black, 0 4px 8px gray;
.modal { @include box-shadow($shadows...); }

// Also works for @include with maps as keyword args
@mixin theme($colors) { /* ... */ }
@include theme(("bg": red, "fg": white)...);
08

@extend と継承

基本の @extend

複製するのでなく、ルールを共有して、あるセレクタが別のセレクタのすべてのスタイルを継承するのが、@extend です。セレクタをまとめてグループ化するのが、コンパイル済み CSS です。共有されたベーススタイルのために、mixin より DRY なのが、@extend ですが、驚くべきセレクタのチェーンを作り得ます。慎重に使うこと。

sass
.message {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

// .success inherits all .message styles
.success {
  @extend .message;
  background: #d4edda;
  border-color: #c3e6cb;
}

.error {
  @extend .message;
  background: #f8d7da;
  border-color: #f5c6cb;
}

// Compiles to: .message, .success, .error { padding: 10px; ... }

複雑なセレクタの拡張

任意のセレクタで機能するのが、@extend です。クラス、要素のセレクタ、疑似クラス、複合セレクタです。.icon.large の拡張が、.icon と .icon.large の両方に一致するルールを継承します。複雑なセレクタの拡張には注意しましょう。予想外のやり方でカスケードし得るのが、生成された CSS であり、出力が肥大します。

sass
// You can extend any selector, not just classes
a:hover {
  text-decoration: underline;
}

.link-card:hover {
  @extend a:hover;  // inherits :hover rule
  color: blue;
}

// Extending with compound selectors
.icon {
  display: inline-block;
}

.icon.large {
  font-size: 24px;
}

.icon-x { @extend .icon.large; }  // extends BOTH rules

@extend のチェーン

@extend がチェーンされます:B が A を拡張し、C が B を拡張すれば、C が両方から継承します。それに応じてセレクタをグループ化するのが、コンパイル済み CSS です。大きなセレクタのリストと驚くべき詳細度を、深いチェーンが作り得ます。ほとんどの再利用のシナリオには、チェーンされた @extends より、mixin がより予測可能です。

sass
.base {
  display: block;
  padding: 8px;
}

.intermediate {
  @extend .base;
  background: #eee;
}

.final {
  @extend .intermediate;
  color: red;
}

// .final inherits from .intermediate which inherits from .base
// Compiles to: .base, .intermediate, .final { display: block; padding: 8px; }
//              .intermediate, .final { background: #eee; }
//              .final { color: red; }

@extend !optional

ターゲットセレクタが存在しなければ、例外を投げるのではなく、拡張を静かにスキップするのが、@extend への !optional の追加です。省略可能か条件付きでロードされるセレクタの拡張に有用です。!optional がなければ、ターゲットが欠けていれば、コンパイルが失敗するのが、@extend です。

sass
// !optional prevents errors if the selector doesn't exist
.fluent {
  @extend .nonexistent !optional;  // no error, just skipped
  color: blue;
}

// Without !optional, extending a missing selector throws:
// ".nonexistent failed to @extend"
// Use !optional when the extension target may or may not exist
// (e.g., optional theme classes from a third-party library)

@extend 対 @include mixin

セレクタをグループ化するのが(再利用が重いときより小さい CSS)、@extend ですが、隠れた結合を作ります。宣言を複製するのが(より大きい CSS)、@include の mixins ですが、自己完結しており設定可能です。新しいコードには mixins を推奨しましょう — 予測可能なのです。1 つのファイル内のセマンティックな関係のために、主に @extend を。

sass
// @extend - shares one rule, groups selectors
.btn { padding: 8px; }
.primary { @extend .btn; background: blue; }
// -> .btn, .primary { padding: 8px; }

// @mixin - duplicates declarations each use
@mixin btn { padding: 8px; }
.primary { @include btn; background: blue; }
// -> .primary { padding: 8px; background: blue; }

// When to use which:
// @extend: share base styles semantically (DRY selectors)
// @mixin: configurable repeated declarations (with args)
// Avoid @extend across module boundaries (can cause side effects)
09

プレースホルダセレクタ(%placeholder)

%placeholder の基本

拡張されるためだけに存在するルールであるのが、%placeholder のセレクタ(例:%base-message)です。それ自体では、CSS へ出力されることは決してありません。これが、本物のクラス上の @extend が引き起こし得る、未使用のベースクラスの問題を避けます。継承だけを意図したスタイルの共有の、最もきれいな方法が、プレースホルダです。

sass
// %placeholder selectors are NOT output in CSS
// They only appear when @extended
%base-message {
  padding: 10px;
  border-radius: 4px;
}

.success { @extend %base-message; background: green; }
.error { @extend %base-message; background: red; }

// Compiles to (notice %base-message is gone):
// .success, .error { padding: 10px; border-radius: 4px; }
// .success { background: green; }
// .error { background: red; }

プレースホルダ対クラス

本物のクラスを @extend するとき、HTML で決して使われなくても、そのクラスが出力に現れます。これを解決するのが、プレースホルダです。拡張された場所でのみ出力されるのが、%base です。ベースが HTML で直接使われるときは、本物のクラスを、継承のためだけなら、プレースホルダを使いましょう。

sass
// Class as extend target - the class IS output
.message { padding: 10px; }  // appears in CSS even if unused
.success { @extend .message; }

// Placeholder as extend target - NOT output
%message { padding: 10px; }  // never appears in CSS
.success { @extend %message; }

// Result is identical for .success, but the placeholder
// version doesn't pollute the CSS with an unused .message rule.
// Use placeholders for internal/inheritance-only base styles.

@extend でのプレースホルダ

複数のプレースホルダをセレクタが @extend でき、共有されたスタイルのセットを組み合わせられます。未使用のベースクラスを出力せず、再利用可能な積み木を構成できます。多くの具体的なコンポーネントにわたり共有される、デザインシステムのプリミティブ(カード、ボタン、入力)に、プレースホルダが輝きます。

sass
%card-base {
  background: white;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 16px;
}

%card-shadow {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

// Combine multiple placeholders
.featured-card {
  @extend %card-base;
  @extend %card-shadow;
  border-color: gold;
}

複数のプレースホルダの共有

複数のセレクタが同じプレースホルダを @extend するとき、出力でそれらをまとめてグループ化し、コンパクトな CSS を作るのが、Sass です。Sass での最も効率的なスタイルの共有の形式が、これです。ランタイムの CSS クラスの肥大なしで、継承/構成の形式を可能にするのが、プレースホルダです。

sass
%button { padding: 8px 16px; border: none; cursor: pointer; }
%rounded { border-radius: 4px; }
%shadow { box-shadow: 0 1px 3px rgba(0,0,0,0.2); }

// Many components share the same placeholders
.btn-primary { @extend %button; @extend %rounded; @extend %shadow; background: blue; }
.btn-secondary { @extend %button; @extend %rounded; background: gray; }
.btn-ghost { @extend %button; background: transparent; }

// Sass deduplicates: %button's rule is shared across all three

プレースホルダのユースケース

再利用可能なユーティリティのパターンに理想的なのが、プレースホルダです。中央寄せ、clearfix、アクセシビリティ(視覚的に隠す)、デザインシステムのプリミティブです。これらのパターンを 1 箇所に保ち、使われない限り出力を避けます。設定不可のユーティリティスタイルを共有するきれいな方法が、これです。

sass
// 1. Design system primitives
%abs-center {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

// 2. Clearfix
%clearfix::after {
  content: "";
  display: table;
  clear: both;
}

// 3. Visually hidden (accessibility)
%visually-hidden {
  position: absolute;
  width: 1px; height: 1px;
  overflow: hidden;
  clip: rect(0 0 0 0);
}

.modal { @extend %abs-center; }
.container { @extend %clearfix; }
.sr-only { @extend %visually-hidden; }
10

関数(@function)

関数の定義

値を @return する、再利用可能な計算を定義するのが、@function です。プロパティの値の中で呼ばれるのが(宣言を出力する mixins と違い)、関数です。単位の変換、色の数学、レスポンシブなスケーリングのような計算に関数を使いましょう。任意の Sass データ型が、戻り値にできます。

sass
// @function defines a function that returns a value
@function rem($px) {
  $base: 16px;
  @return ($px / $base) * 1rem;
}

// Use it like a CSS function
body { font-size: rem(16); }      // 1rem
h1 { font-size: rem(32); }        // 2rem
.small { font-size: rem(12); }    // 0.75rem

// Functions return values; mixins output CSS rules

関数の引数とデフォルト

mixins と同様に、デフォルト引数、名前付き引数、可変引数(...)を関数がサポートします。呼び出しが便利になるのが、デフォルトです。多くの省略可能なパラメータを持つ関数の読みやすさを改善するのが、名前付き引数です。任意の数の値を受け付けるのが、可変引数により関数です。

sass
@function spacing($factor: 1, $base: 8px) {
  @return $base * $factor;
}

// Use defaults
.card { padding: spacing(); }       // 8px
.card-lg { padding: spacing(2); }   // 16px

// Override by name
.section { padding: spacing($base: 10px); }  // 10px
.hero { padding: spacing(3, 10px); }         // 30px

// Variable arguments work too
@function max-of($nums...) {
  @return ...; // implement with reduce
}

組み込み関数の概観

色、数学、文字列、リスト、マップのための豊かな組み込み関数を ship するのが、Sass です。モジュールへ(@use でロードされる、sass:math、sass:color、sass:string、sass:list、sass:map、sass:meta)整理しているのが、モダンな Sass です。グローバルの関数名が依然機能しますが、名前空間化されたモジュールの関数が推奨のため、非推奨です。

sass
// Color functions
lighten(#000, 50%)       // gray
rgba(#fff, 0.5)          // semi-transparent white
mix(red, blue)           // purple

// Math functions
percentage(0.5)          // 50%
round(3.6)               // 4
min(10px, 20px)          // 10px

// String functions
to-upper-case("abc")     // "ABC"
str-length("hello")      // 5

// List/Map functions
length(1 2 3)            // 3
map-get(("a": 1), "a")   // 1

// Modern Sass uses modules: @use 'sass:math'; math.div(10, 2)

実用的な関数の例

再利用可能な計算のカプセル化に優れるのが、関数です:単位の変換(px/em/rem)、マップ経由の z-index の管理、デザイントークンのルックアップです。これらを関数で一元化すれば、一貫性が確保され、(ベースフォントサイズの更新のような)変更が、自動的にあらゆる所へ伝播します。

sass
// Convert px to em relative to a context
@function em($px, $context: 16px) {
  @return ($px / $context) * 1em;
}

// Generate a z-index from a scale map
$z-indexes: (
  "base": 0,
  "dropdown": 100,
  "modal": 200,
  "toast": 300,
);
@function z($name) {
  @return map-get($z-indexes, $name);
}

// Usage
body { font-size: em(18px); }              // 1.125em
.modal { z-index: z("modal"); }            // 200
.toast { z-index: z("toast"); }            // 300

再帰関数

@if の条件と自己呼び出し経由の再帰を、Sass の関数がサポートします。これで、階乗、フィボナッチ、その他の計算されたシーケンスが可能になります。しかし、末尾呼び出しの最適化がなく遅いのが、Sass の再帰です。本物のスタイルシートでの深い再帰は避けましょう。反復の計算には、(@for の)ループを推奨しましょう。

sass
// Functions can call themselves (recursion)
@function factorial($n) {
  @if $n <= 1 {
    @return 1;
  } @else {
    @return $n * factorial($n - 1);
  }
}

.power { width: factorial(5) * 1px; }  // 120px

// Fibonacci
@function fib($n) {
  @if $n < 2 { @return $n; }
  @return fib($n - 1) + fib($n - 2);
}

// Note: deep recursion is slow in Sass - use sparingly
11

制御ディレクティブ

@if / @else if / @else

比較に基づき条件付きでスタイルを出力するのが、@if/@else if/@else です。等価には == と != を使うのが、Sass です(=== ではなく)。真偽演算子が、「and」、「or」、「not」です(&&、||、! ではなく)。mixin と関数内のテーマ切り替え、フィーチャーフラグ、レスポンシブロジックに有用です。

sass
@mixin theme($mode) {
  @if $mode == dark {
    background: #222;
    color: #eee;
  } @else if $mode == light {
    background: #fff;
    color: #333;
  } @else {
    background: gray;
    color: black;
  }
}

.dark { @include theme(dark); }
.light { @include theme(light); }
.auto { @include theme(auto); }

// Comparison operators: ==, !=, <, >, <=, >=, and, or, not

@for ループ

変数を開始値から終了値まで反復するのが、@for です。含むのが(終了を含めます)、「through」で、含まないのが(終了を除外します)、「to」です。グリッド列、段階的なアニメーション、番号付きのユーティリティクラスの生成によく使われます。セレクタへカウンタを挿入するには、#{} の補間を使いましょう。

sass
// @for $var from <start> through <end>  (inclusive)
@for $i from 1 through 3 {
  .col-#{$i} { width: 100% / $i; }
}
// .col-1 { width: 100%; }  .col-2 { width: 50%; }  .col-3 { width: 33.333%; }

// 'to' is EXCLUSIVE (excludes the end)
@for $i from 1 to 3 {
  .item-#{$i} { order: $i; }
}
// .item-1, .item-2  (no .item-3)

// Use 'through' for inclusive, 'to' for exclusive ranges

@each ループ(リスト)

リスト上を反復し、各アイテムを変数へ束縛するのが、@each です。設定のリストから、テーマ化されたバリアント、アイコンクラス、ユーティリティクラスを生成するのに理想的です。(name、color のタプルのような)ペアデータのため、リストのリストが、反復ごとの複数の変数へ展開できます。

sass
// Iterate over a list
$icons: user, home, settings, search;

@each $name in $icons {
  .icon-#{$name} {
    background-image: url("/icons/#{$name}.svg");
  }
}
// .icon-user, .icon-home, .icon-settings, .icon-search

// Multiple values (unpacking)
@each $name, $color in (success green), (error red) {
  .alert-#{$name} { color: $color; }
}

マップでの @each

反復ごとに、キーと値の両方を束縛するのが、マップ上の @each です。設定マップから、レスポンシブなユーティリティ、テーマのバリアント、ブレークポイントを意識したクラスを生成する標準的な方法が、これです。モダンな Sass での、挿入順に従うのが、マップの反復順序です。

sass
$breakpoints: (
  "sm": 576px,
  "md": 768px,
  "lg": 1024px,
  "xl": 1280px,
);

// Iterate key-value pairs of a map
@each $name, $size in $breakpoints {
  .container-#{$name} {
    max-width: $size;
    margin: 0 auto;
  }
}
// .container-sm, .container-md, .container-lg, .container-xl

// Also destructuring lists of maps for richer config
$buttons: (("primary", blue), ("danger", red));

@while ループ

条件が false になるまでループするのが、@while です。カウンタを手動で更新しなければなりません。@for が合わない、非線形の進行(各ステップでの倍増など)に使いましょう。ループが終端することを必ず確保しましょう — 増加の忘れが、コンパイルをハングさせる無限ループの原因になります。

sass
// @while repeats while a condition is true
$i: 1;
@while $i <= 5 {
  .mt-#{$i} { margin-top: $i * 4px; }
  $i: $i + 1;
}
// .mt-1 { margin-top: 4px; } ... .mt-5 { margin-top: 20px; }

// Unlike @for, you control the increment
// WARNING: always increment/decrement to avoid infinite loops!
$i: 6;
@while $i > 0 {
  .delay-#{$i} { transition-delay: $i * 100ms; }
  $i: $i - 1;
}
12

リストとマップ

リスト

Sass の配列のタイプであるのが、リストです。スペースかカンマで区切られます。(ほとんどの言語と違い)1 起点なのが、インデックスです。最初のアイテムを返すのが、nth($list, 1) です。末尾から数えるのが、負のインデックスです。1 要素のリストとして扱われるのが、単一の値です。ネストできるのが、リストです。

sass
// Lists are ordered collections (like arrays)
// Separated by spaces or commas
$sizes: 10px 20px 30px;          // space-separated
$colors: red, green, blue;       // comma-separated
$mixed: (1px 2px) (3px 4px);     // nested lists

// Single value is also a list of length 1
$one: 5px;

// Indexes are 1-based!
$list: a b c;
nth($list, 1);   // a  (NOT 0-indexed)
nth($list, -1);  // c  (negative = from end)
length($list);   // 3

リストの関数

アクセスの関数が、length()、nth()、index() で、新しいリストを返すのが(不変であるのが、リストです)、append()、join()、insert-nth() です。複数のリストからの要素をペアにするのが、zip() です。リストの区切りを返すのが、separator() です。反復には、@each を。sass:list モジュールに住むのが、モダンな API です。

sass
$list: a b c;

// Access
length($list);          // 3
nth($list, 2);          // b
index($list, b);        // 2 (position of b, or null)

// Modify (return NEW list - lists are immutable)
append($list, d);       // a b c d
join(a b, c d);         // a b c d
join((a b), (c d), comma); // a, b, c, d

// Insert
insert-nth($list, 2, x);   // a x b c

// Misc
zip(1 2, a b);          // (1 a) (2 b) - pairs elements

マップ

キー・バリューのコレクションであるのが(連想配列)、マップです。一意でなければならないのが、キーで、ネストしたマップを含む任意の Sass のタイプにできるのが、値です。値を読むのが、map-get() で、存在を確認するのが、map-has-key() です。デザイントークン、ブレークポイント、テーマのパレットをモデル化する標準的な方法が、マップです。

sass
// Maps are key-value pairs (like objects/dictionaries)
$colors: (
  "primary": #3498db,
  "secondary": #2ecc71,
  "danger": #e74c3c,
  "warning": #f39c12,
);

// Access values
map-get($colors, "primary");      // #3498db

// Check existence
map-has-key($colors, "success");  // false

// Keys must be unique; values can be any type (even nested maps)
$breakpoints: (
  "mobile": (max: 767px),
  "desktop": (min: 768px),
);

マップの関数

値を読むのが、map-get() で、リストを返すのが、map-keys()/map-values()、マップを組み合わせるのが(テーマの拡張に最適)、map-merge()、キーを削除するのが、map-remove() です。不変であるのが、マップです。新しいマップを返すのが、関数です。sass:map モジュールの下に名前空間化されているのが、モダンな API です。

sass
$colors: ("a": 1, "b": 2);

// Access
map-get($colors, "a");          // 1
map-has-key($colors, "c");      // false

// Keys & values as lists
map-keys($colors);              // ("a", "b")
map-values($colors);            // (1, 2)

// Merge (combines two maps; second wins on conflicts)
$base: ("x": 1, "y": 2);
$override: ("y": 99, "z": 3);
map-merge($base, $override);    // ("x": 1, "y": 99, "z": 3)

// Remove keys
map-remove($colors, "a");       // ("b": 2)

反復と分割代入

マップ(key、value)とリストのリストを分割代入し、反復ごとに複数の変数を束縛するのが、@each です。これが、設定データを生成された CSS へ変えます。デザインシステムのための強力なパターンです。マップと組み合わせれば、単一の設定マップから、ユーティリティクラスのフレームワーク全体を駆動できます。

sass
$grid: (
  "sm": 576px,
  "md": 768px,
  "lg": 1024px,
);

// @each destructures map into key+value
@each $name, $size in $grid {
  @media (min-width: $size) {
    .container-#{$name} { max-width: $size; }
  }
}

// Nested destructuring with lists of lists
$config: (("primary", blue, white), ("danger", red, white));
@each $name, $bg, $fg in $config {
  .btn-#{$name} { background: $bg; color: $fg; }
}
13

色の関数

lighten / darken

パーセンテージにより、色の明るさを動かすのが、lighten() と darken() です。(どのチャンネルが変わるか明示的な)sass:color からの color.adjust() が推奨のため、非推奨です。既に極端な色での驚くべき結果を作り得るのが、素の lighten/darken です。HSL ベースの調整を推奨しましょう。

sass
$base: #3498db;

.light { background: lighten($base, 20%); }   // lighter blue
.dark  { background: darken($base, 20%); }    // darker blue

// Note: lighten/darken are deprecated in modern Sass
// Prefer sass:color adjust() for clarity:
@use 'sass:color';
.adjusted {
  // same effect, explicit
  background: color.adjust($base, $lightness: 20%);
  border-color: color.adjust($base, $lightness: -20%);
}

rgba / rgb / 透明度

任意の色へ透明度を加えるのが、rgba($color, $alpha) です。最もよくある色の関数です。4 つの数値引数も受け付けるのが、rgba() です。明示的な alpha 制御のための color.adjust($alpha: ...) を、モダンな sass:color モジュールが提供します。モダンな Sass でも有効なのが、CSS Color 4 のスペースの構文(rgb(r g b / a%))です。

sass
$brand: #3498db;

// Add alpha to any color
.semi { background: rgba($brand, 0.5); }    // #3498db at 50%
.fade { background: rgba($brand, 0.1); }    // very transparent

// rgba() also accepts 4 numeric args
.box { background: rgba(52, 152, 219, 0.8); }

// Modern alternative: color.adjust for alpha
@use 'sass:color';
.glass { background: color.adjust($brand, $alpha: -0.5); }

// rgb() and rgba() with space syntax (CSS Color 4)
.modern { background: rgb(52 152 219 / 80%); }

mix / 色のブレンド

2 つの色を混ぜ合わせるのが、mix($color1, $color2, $weight) です。$weight が $color1 のパーセンテージです(デフォルト 50%)。色合いには mix($color, white) を、色影には mix($color, black) を使いましょう。これは、lighten()/darken() より、しばしばより自然に見えます。モダンな名前空間化された等価物が、color.mix です。

sass
// mix() blends two colors by a weight (default 50%)
$mix: mix(red, blue);          // purple (50/50)
$mix30: mix(red, blue, 30%);   // 30% red, 70% blue (bluer)

// Useful for generating tints and shades
$base: #3498db;
.tint  { background: mix($base, white, 20%); }  // 20% blue, 80% white
.shade { background: mix($base, black, 20%); }  // 20% blue, 80% black

// sass:color module
@use 'sass:color';
.blended { background: color.mix(red, blue, 50%); }

adjust-color / scale-color / change-color

3 つの精密な色の道具です:チャンネルへ差分を加えるのが、color.adjust() で、(より安全な — 決して行き過ぎません)パーセンテージによりチャンネルを min/max へスケールするのが、color.scale()、チャンネルを絶対値へ設定するのが、color.change() です。非推奨の別名が、グローバルの adjust-color/scale-color/change-color です。

sass
@use 'sass:color';
$base: #3498db;

// adjust: ADDS to channels (absolute change)
.a { background: color.adjust($base, $red: 30, $alpha: -0.3); }

// scale: SCALES channels by % (relative change, stays in range)
.s { background: color.scale($base, $lightness: 50%); }

// change: SETS channels to exact values (replaces)
.c { background: color.change($base, $lightness: 50%, $hue: 0); }

// adjust moves by a delta, scale shrinks/grows toward min/max,
// change overwrites with a fixed value.

hue / saturation / complement

HSL のチャンネルを読むのが、color.hue/saturation/lightness です。条件ロジックに有用です。逆の hue の色を返すのが(アクセントに最適)、color.complement() で、彩度を落とすのが、color.grayscale()、RGB の反転を行うのが、color.invert() です。HSL 値から色を構築するのが、color.hsl() です。プログラム的なパレットの生成を可能にするのが、これらです。

sass
@use 'sass:color';
$c: #3498db;

// Read HSL channels
color.hue($c);           // 204deg
color.saturation($c);    // 70%
color.lightness($c);     // 53%

// Derive new colors
.complement { background: color.complement($c); }     // opposite hue
.grayscale  { background: color.grayscale($c); }       // desaturated
.invert     { background: color.invert($c); }          // RGB inverse

// Build from HSL
.from-hsl { background: color.hsl(204, 70%, 53%); }
14

数学の操作

基本の算術

数値上の +、-、*、/、% をサポートし単位を扱うのが、Sass です。分離のために CSS が / を使うため(font: 16px/1.5)、除算としての素の / が非推奨です — sass:math からの math.div() か括弧を使いましょう。+ と - のためには、単位が互換的でなければなりません。単位付きの 2 値の乗算が、通常エラーです。

sass
$base: 16px;

// Sass does math on numbers (with unit handling)
width: 100% - 20px;   // ERROR - incompatible units
width: 100px + 20px;  // 120px
width: 100px * 2;     // 200px
width: 100px / 2;     // 50px (use math.div in modern Sass)
width: (100px / 2);   // 50px (parenthesized = math, not CSS)

// Modern division (the / operator is deprecated for division)
@use 'sass:math';
width: math.div(100px, 2);   // 50px
width: math.div(100, 3);     // 33.333...

単位の変換

物理単位の間(px、in、cm、mm、pt、pc)を自動変換するのが、Sass ですが、px/em/rem/% の間では「ありません」。自分で変換関数を書かなければなりません。よくあるパターンが、ベースフォントサイズで割る、rem($px) の関数です。プロジェクトのスペーシングスケールが一貫するよう、単位の変換を一元化しましょう。

sass
$base-font: 16px;

// Convert px to rem
@function rem($px) {
  @return math.div($px, $base-font) * 1rem;
}
h1 { font-size: rem(32px); }   // 2rem

// Convert px to em (relative to context)
@function em($px, $context: 16px) {
  @return math.div($px, $context) * 1em;
}

// Sass does NOT auto-convert between px/em/rem/%
// You must compute the ratio yourself.
// 1in = 96px, 1cm = 37.8px, 1pt = 1.33px (these DO auto-convert)

数学の関数

round()、ceil()、floor()、abs()、min()、max()、percentage()、(新しい)三角と root の関数、そして math.$pi のような定数を提供するのが、sass:math です。ここでの min()/max() が、Sass の関数です(CSS の min()/max() とは異なります — 本物の CSS の min/max のためには、引用符なしで CSS の方を使いましょう)。数学を必ず明示的に import しましょう。

sass
@use 'sass:math';

// Rounding
math.round(3.6);     // 4
math.ceil(3.1);      // 4
math.floor(3.9);     // 3

// Absolute & bounds
math.abs(-5);        // 5
math.min(10px, 20px);  // 10px
math.max(10px, 20px);  // 20px

// Percentage conversion
math.percentage(0.5);  // 50%  (math.percentage, or global percentage)

// Trig & constants (Sass 1.65+)
math.sin(math.$pi);    // ~0
math.cos(0);           // 1
math.sqrt(16);         // 4

剰余と除算

モダンな除算関数が、math.div() です。CSS のリストの区切り(font: 16px/1.5 のような)のために予約されるのが、/ の演算子です。余りを返すのが、math.mod() です。2 つの数値が加算できるか確認するのが、math.compatible() です。算術のためには、必ず @use 'sass:math' をしましょう。除算のためのグローバルの / が非推奨であり、取り除かれます。

sass
@use 'sass:math';

// Modulo (remainder)
math.unit(10px);     // px
math.compatible(10px, 5px);  // true (can add)
math.is-unitless(5);          // true

// Division MUST use math.div (the / operator is for lists/CSS)
$result: math.div(100, 3);    // 33.333...

// Modulo
$rem: math.mod(10, 3);        // 1

// Generating a grid with modulo
@for $i from 1 through 12 {
  .col-#{$i} { width: math.div($i, 12) * 100%; }
}

比較とロジックの演算子

等価には == と != を使うのが、Sass です。キーワードの「and」、「or」、「not」であるのが、真偽の演算子です(C スタイルの &&/||/! ではありません)。優先順位を明確にするには、括弧を使いましょう。mixin、関数、制御ディレクティブ内の @if の条件を駆動するのが、これらの演算子です。truthy な値が、false と null 以外のすべてです。

sass
// Comparison: ==, !=, <, >, <=, >=
@if $width > 100px { /* ... */ }
@if $count == 3 { /* ... */ }
@if $mode != "dark" { /* ... */ }

// Boolean logic: and, or, not (NOT &&, ||, !)
$enabled: true;
$mobile: false;

@if $enabled and not $mobile {
  .desktop-only { display: block; }
}

@if $mode == "dark" or $mode == "night" {
  background: black;
}

// Use parentheses to group
@if ($a > 1 and $b < 10) or $c == 5 { /* ... */ }
15

文字列の関数

quote / unquote

文字列を引用符で包むのが、quote() で、取り除くのが、unquote() です。引用符付きの文字列(コンテンツ、フォント名に使われる)と、引用符なしの文字列(識別子、クラス名に使われる)を区別するのが、Sass です。両方を受け付けるのが、多くの関数ですが、出力の整形とセレクタの生成のために、区別が効きます。

sass
// quote() forces quotes around a string
$unquoted: Helvetica;
$quoted: quote($unquoted);   // "Helvetica"

// unquote() removes quotes
$quoted: "Arial";
$plain: unquote($quoted);    // Arial

// Useful when a string needs to be quoted for output
.url { background: url(quote("/img/x.png")); }
// url("/img/x.png")

// Quoted vs unquoted matters for some CSS values
// Class names and property names are usually unquoted

大文字小文字の関数

文字列の大文字小文字を変換するのが、to-upper-case() と to-lower-case() です。一貫したクラス名、コンテンツ値の生成や、入力の正規化に有用です。#{} の補間と組み合わせれば、変数から動的なセレクタとコンテンツを構築できます。sass:string に住むのが、モダンな名前空間化された版です。

sass
// Change string case
$upper: to-upper-case("hello");   // "HELLO"
$lower: to-lower-case("WORLD");   // "world"

// Practical: generate uppercase class names
$states: success, warning, error;
@each $s in $states {
  .badge-#{to-upper-case($s)} {
    content: "#{to-upper-case($s)}";
  }
}

// .badge-SUCCESS { content: "SUCCESS"; } etc.

str-length / str-slice / str-index

sass:string の関数:文字数を返すのが、string.length() で、部分文字列を返すのが(1 起点、末尾からは負)、string.slice($str, $start, $end)、部分文字列の位置を見つけるのが(1 起点、欠けていれば null)、string.index() です。組み込みの split が Sass になく — index() と slice() を使うループで実装しましょう。

sass
@use 'sass:string';

$str: "Hello, World";

// Length (character count)
string.length($str);    // 12

// Slice (substring) - 1-based, supports negatives
string.slice($str, 1, 5);   // "Hello"
string.slice($str, 8);      // "World"
string.slice($str, -5);     // "World" (from end)

// Index of substring (1-based, or null if not found)
string.index($str, "World");  // 8
string.index($str, "xyz");    // null

// Split is not built-in - use a custom function with index+slice

str-insert / str-replace

1 起点の位置へ部分文字列を挿入するのが(追記するには大きい数を使う)、string.insert($string, $insert, $position) です。部分文字列を交換するのが(デフォルトですべて、または制限された数)、string.replace($string, $to-replace, $replace-with, $limit?) です。プログラム的なクラス名とコンテンツの生成に、これらが不可欠です。

sass
@use 'sass:string';

// str-insert: insert at position (1-based)
string.insert("Hello", "!", 6);    // "Hello!"
string.insert("World", "Hello ", 1);  // "Hello World"

// Modern Sass (1.55+) has string.replace
string.replace("a-b-c", "-", "_");        // "a_b_c" (replace all)
string.replace("a-b-c", "-", "_", 1);     // "a_b-c" (limit 1)

// Build dynamic strings
$prefix: "icon";
$name: string.insert($prefix, "-user", 100);  // "icon-user"

文字列の補間のパターン

任意の Sass 値(数値、リスト、色、真偽値)を文字列表現へ変換し、埋め込むのが、#{} の補間です。動的なセレクタ、プロパティ名、コンテンツ値、URL を構築するのに使いましょう。素の変数が許されない CSS のテキスト出力と、Sass の値の間の橋渡しが、補間です。

sass
$prefix: "btn";
$modifier: "primary";

// #{} converts any value to a string and embeds it
.#{$prefix}-#{$modifier} { /* ... */ }   // .btn-primary

// Interpolating numbers, lists, booleans
$count: 3;
.item-#{$count} { order: $count; }       // .item-3 { order: 3; }

// Interpolating in @include and @media
@mixin respond-to($bp) {
  @media (max-width: $bp) { @content; }
}

// Interpolating function calls
.content::after {
  content: "#{to-upper-case('hello')}";
}
16

@at-root

基本の @at-root

現在のネストのコンテキストを出て、スタイルシートのトップレベルでネストしたルールを出力するのが、@at-root です。@at-root がなければ、.parent 内の .child が、.parent .child(子孫)へコンパイルされます。単なる .child になるのが、@at-root です。関連するルールをソースでまとめて保ちつつ、フラットなセレクタを出力させます。

sass
.parent {
  color: blue;

  // @at-root jumps out of the nesting
  @at-root .child {
    color: red;
  }
}

// Compiles to (note: .child is NOT nested under .parent):
// .parent { color: blue; }
// .child { color: red; }   <- top-level, not .parent .child

// Useful for defining sibling/related rules inside a block
// without creating a descendant selector.

セレクタ付きの @at-root

親セレクタの一部を選択的に保つため、& と @at-root を組み合わせましょう。(.component .wrapper の代わりに).wrapper .component を出力するのが、@at-root .wrapper & です。コンテキストを前置します。コンポーネントコードと同じ場所に保ちつつ、テーマ/コンテキストの上書きを書くきれいな方法が、これです。

sass
.component {
  width: 100px;

  // Combine @at-root with & to keep part of the parent
  @at-root .wrapper & {
    background: yellow;
  }
  // -> .wrapper .component { background: yellow; }

  // Useful for context overrides without deep nesting
  @at-root .dark-theme & {
    color: white;
  }
  // -> .dark-theme .component { color: white; }
}

BEM のための @at-root

BEM の修飾子クラス(.block--active)を、子孫でなく兄弟として生成するのを助けるのが、@at-root です。@at-root がなければ、.block の内側に .block--active をネストすると、.block .block--active が作られます(間違い — それは、ブロック内のアクティブなブロックを意味します)。トップレベルで修飾子を出力するのが、@at-root で、正しい BEM の出力です。

sass
.block {
  // State classes as siblings, not descendants
  @at-root {
    .block--active { border-color: blue; }
    .block--disabled { opacity: 0.5; }
  }

  // Or inline form
  @at-root .block--hidden { display: none; }
}

// Compiles to top-level siblings:
// .block { ... }
// .block--active { border-color: blue; }
// .block--disabled { opacity: 0.5; }
// .block--hidden { display: none; }

// Avoids accidentally generating .block .block--active

メディアクエリでの @at-root

セレクタのネストからルールを持ち上げつつ、@media ブロックの中に保つのが、@at-root (with: media) です。逆であるのが、@at-root (without: media) です。保たれるコンテキスト(rule、media、supports)を制御するのが、with/without の句です。高度ですが、頑健なレスポンシブ mixin ライブラリの構築には不可欠です。

sass
.component {
  width: 100%;

  // @at-root lifts media queries to the top level
  @at-root (with: media) {
    @media (min-width: 768px) {
      & { width: 50%; }
    }
  }
  // -> @media (min-width: 768px) { .component { width: 50%; } }
}

// Default @at-root (without: rule) lifts OUT of everything
// @at-root (with: media) keeps the @media context but exits rules
// Useful in complex nested mixins to control scope precisely

without(with)付きの @at-root

どのネストのコンテキストから @at-root が脱出するかを制御するのが、(without: ...)と(with: ...)の句です。よくあるコンテキスト:「rule」(セレクタ)、「media」(@media)、「supports」(@supports)、か「all」です。(without: rule)が、@media を保ちつつセレクタを出ます。高度な mixin とライブラリのパターンを可能にするのが、この精密なスコープの制御です。

sass
.parent {
  @media (min-width: 768px) {
    .child {
      width: 50%;

      // Exit only the rule, keep the @media
      @at-root (without: rule) {
        .sibling { width: 25%; }
      }
      // -> @media (min-width: 768px) { .sibling { width: 25%; } }

      // Exit everything (default)
      @at-root .top { color: red; }
      // -> .top { color: red; }  (no @media, no parent)
    }
  }
}
17

@content

@content の基本

@include { ... } 経由で渡されたスタイルのブロックのためのプレースホルダーであるのが、@mixin 内の @content です。呼び出し場所で、@content を置き換えるのが、含められたブロックです。これにより、mixins がカスタムスタイルを包めます。メディアクエリ、keyframes、内側のコンテンツが使用ごとに変わる任意の「ラッパー」のパターンには、不可欠です。

sass
// @content marks where the included block is injected
@mixin highlighted {
  background: yellow;
  font-weight: bold;

  @content;  // the block passed to @include goes here
}

.title {
  @include highlighted {
    color: red;       // injected where @content was
    font-size: 20px;
  }
}

// Compiles to:
// .title { background: yellow; font-weight: bold; color: red; font-size: 20px; }

引数付きの @content

mixin から含められたブロックへ値を渡すのが、@content ($args) で、「using ($vars)」でそれらを受け取ります。これにより、mixins が(現在のブレークポイント名のような)コンテキストを、呼び出し側のブロックへ提供できます。ループの状態を消費者へ公開する必要のある、反復/ラッパーの mixins の構築に強力です。

sass
// Pass values back to the included block (Sass 3.3+)
@mixin each-breakpoint {
  $breakpoints: (sm: 576px, md: 768px, lg: 1024px);

  @each $name, $size in $breakpoints {
    @media (min-width: $size) {
      @content ($name, $size);
    }
  }
}

// Receive via #{...} - actually use the block like a function
@include each-breakpoint using ($name, $size) {
  .container-#{$name} { max-width: $size; }
}

メディアクエリのための @content

最もよくある @content のユースケース:正しい @media クエリでスタイルを包む、respond-to の mixin です。レスポンシブなスタイルのブロックを、呼び出し側が渡し、正しいメディアクエリの中へそれを置くのが、mixin です。これで、レスポンシブなコードが読みやすくなり、ブレークポイントの定義が 1 箇所に一元化されます。

sass
// Classic responsive mixin pattern
@mixin respond-to($breakpoint) {
  @if $breakpoint == phone {
    @media (max-width: 600px) { @content; }
  } @else if $breakpoint == tablet {
    @media (min-width: 601px) and (max-width: 900px) { @content; }
  } @else if $breakpoint == desktop {
    @media (min-width: 901px) { @content; }
  }
}

.sidebar {
  width: 300px;

  @include respond-to(phone) {
    width: 100%;
    float: none;
  }

  @include respond-to(desktop) {
    width: 350px;
  }
}

@content のパターン

多くの再利用可能なパターンを支えるのが、@content です:@supports のラッパー、keyframes のジェネレータ、BEM のための修飾子クラスのジェネレータです。mixin がボイラープレート(セレクタ、at-rule、名前空間)を扱い、呼び出し側が本文を供給できるのが、それぞれです。柔軟で構成可能な API を、よく構成された Sass ライブラリが提供する方法が、これです。

sass
// Wrapper for @supports (feature queries)
@mixin supports-flex { @supports (display: flex) { @content; } }

// Keyframes generator
@mixin keyframes($name) {
  @keyframes #{$name} { @content; }
}

@include keyframes(fade-in) {
  from { opacity: 0; }
  to   { opacity: 1; }
}

// Modifier generator
@mixin modifier($name) {
  &--#{$name} { @content; }
}
.button {
  @include modifier(primary) { background: blue; }
  @include modifier(danger) { background: red; }
}

@content のユースケース

コンテキストのラッパー(media/supports/keyframes)、拡張のフック(ベーススタイル + カスタムの追加)、条件付きの出力を可能にするのが、@content です。高階関数の Sass の等価物です:フレームワークが、mixin で、コールバックが、@content です。柔軟で再利用可能なスタイルのユーティリティを構築するには、@content をマスターしましょう。

sass
// 1. Context wrappers (@media, @supports, @keyframes)
@mixin mobile { @media (max-width: 767px) { @content; } }

// 2. Reset/normalize hooks
@mixin base-styles {
  box-sizing: border-box;
  margin: 0;
  @content;  // allow components to add more
}

// 3. Debugging/profiling wrappers
@mixin timed {
  $start: systime();
  @content;
  // log elapsed...
}

// 4. Conditional output
@mixin if-dark($is-dark) {
  @if $is-dark { @content; }
}
18

モジュールシステム(@use / @forward)

@use 対 @import

本物のモジュールシステムで @import を置き換えるのが、@use です。名前空間化が衝突を防ぎ、モジュールが 1 回ロードされ(キャッシュ)、- か _ で始まるメンバーがプライベートになり(公開されず)、デフォルトを明示的に設定するのが、「with」です。@import の構造的な問題のすべてを、これが修正します。すべての新しい Sass コードには、@use を。

sass
// @use is the modern module system (replaces @import)
// Key improvements:
// 1. Members are namespaced (no global pollution)
// 2. Modules load ONCE (cached, no duplicate execution)
// 3. Privacy: members starting with - or _ are private
// 4. Explicit configuration with 'with'

// _shapes.scss
$radius: 4px;
@mixin rounded { border-radius: $radius; }
@mixin -internal { /* private */ }   // not exposed

// app.scss
@use 'shapes';          // namespace: shapes
@use 'shapes' as s;     // namespace: s
@use 'shapes' as *;     // no namespace (global)

.card { @include shapes.rounded; }   // via namespace

@forward

自分のものにせず、別のモジュールからメンバーを再エクスポートするのが、@forward です。フォルダの内容を集約する、バレル/インデックスのファイルに完璧です。「hide」でメンバーを除外し、再エクスポートのときの改名に「as prefix-*」を、@forward がサポートします。ライブラリかフォルダのための、きれいな公開 API を作れます。

sass
// @forward re-exports members from another module
// Useful for building index/barrel files

// sass/abstracts/_index.scss
@forward 'variables';    // exposes _variables.scss members
@forward 'functions';
@forward 'mixins';

// Now consumers can import the whole folder at once:
// app.scss
@use 'abstracts' as *;   // gets variables + functions + mixins

// @forward can rename or hide members
@forward 'buttons' hide button-styles;
@forward 'forms' as form-*;  // prefix all members with 'form-'

プライベートメンバー(- 接頭辞)

- か _ で始まる名前のメンバーが、プライベートです。自分のファイル内では使えますが、@use や @forward を通して公開され「ません」。これにより、モジュールが実装の詳細を隠し、公開 API だけを公開できます。内部のヘルパーには - 接頭辞を使い、モジュールのインターフェースをきれいで安定に保ちましょう。

sass
// _math-helpers.scss
@function -internal-double($n) {
  @return $n * 2;
}

@function public-times-two($n) {
  @return -internal-double($n);  // OK - same file
}

// Public function usable via @use
@function scale($n, $factor: 2) {
  @return -internal-double($n) * $factor;
}

// app.scss
@use 'math-helpers';
.val { width: math-helpers.scale(10); }      // OK
// .val { width: math-helpers.-internal-double(10); }  // ERROR - private

モジュールの設定(with)

ロード時に、モジュールの !default 変数を設定するのが、「with ($var: value, ...)」です。@import のグローバル変数の上書きパターンの、モダンでスコープされた置き換えが、これです。モジュールの最初の @use にだけ適用されるのが、設定で、以後の @use ステートメントが、設定されたモジュールを再利用します。ライブラリがテーマ化される方法が、これです。

sass
// _theme.scss
$primary: blue !default;
$radius: 4px !default;

@mixin button {
  background: $primary;
  border-radius: $radius;
}

// app.scss - configure on @use
@use 'theme' with (
  $primary: #ff6600,
  $radius: 8px,
);

.btn { @include theme.button; }
// background: #ff6600; border-radius: 8px;

// 'with' only works for variables marked !default in the module.
// Configuration must happen at the FIRST @use of that module.

モジュールのベストプラクティス

モジュールのベストプラクティス:@use を使う(@import ではなく)、短い明示的な名前空間を推奨、_index.scss で @forward 付きのフォルダを集約、- による内部ヘルパーのプライベート化、!default 変数上の「with」によるライブラリの設定、標準の関数のための組み込み sass:* モジュールの使用、です。コードがモジュール化され、保守可能に保たれます。

sass
// 1. Always use @use, never @import (deprecated)
// 2. Use explicit namespaces for clarity
@use 'sass:math';      // built-in module namespace: math
@use 'variables' as v; // short custom namespace

// 3. Use @forward in _index.scss barrel files
// components/_index.scss
@forward 'buttons';
@forward 'cards';

// 4. Keep members private with - prefix
@function -helper() { @return ...; }

// 5. Configure libraries with 'with', set !default on library vars
$brand: blue !default;

// 6. Use built-in modules: sass:math, sass:color, sass:string,
//    sass:list, sass:map, sass:meta, sass:selector, sass:css
19

デバッグ(@debug / @warn / @error)

@debug

コンパイル中、ソースファイルと行番号付きで、値をターミナルへ印刷するのが、@debug です。ビルドを止めません。変数の検査、実行フローの追跡、開発中の計算の検証に、@debug を使いましょう。ship の前に、@debug のステートメントを取り除くかコメントアウトしましょう。CSS でなく、stderr へ行くのが、出力です。

sass
// @debug prints a message to the console during compilation
$base: 16px;
$size: 24px;

@debug "Calculating size...";
@debug "base is #{$base}, size is #{$size}";
@debug "ratio: " #{math.div($size, $base)};

// Console output during compile:
// _file.scss:5 DEBUG: Calculating size...
// _file.scss:6 DEBUG: base is 16px, size is 24px

// @debug does NOT stop compilation - just logs
// Use it to trace values while developing

@warn

コンパイル中、致命的でない警告をコンソールへ印刷するのが、@warn です — ビルドが続きます。非推奨のお知らせ、フォールバックの挙動、ライブラリでの潜在的な誤用の警告に使いましょう。デフォルトでスタックトレースを含めるのが、@warn で、ユーザーが警告源を突き止められます。@debug のように、CSS の出力に現れません。

sass
// @warn prints a warning to the console (does NOT stop compilation)
@mixin deprecated-mixin {
  @warn "deprecated-mixin is deprecated; use new-mixin instead.";
  /* ... styles ... */
}

// Useful for deprecation notices, potential issues
@warn "Variable $primary is not set, falling back to default.";

// With stack trace for locating the call site
@warn "Invalid value: #{$value}" {
  // optional stack trace via meta.module-functions
}

// @warn is non-fatal - compilation continues.

@error

致命的なエラーを投げ、コンパイルを即座に止めるのが、@error です。関数と mixins への入力の検証に使いましょう — 壊れた CSS を出力するより、明確なメッセージ付きの早期の誤用の捕捉が勝ります。スタックトレースを含めるのが、@error です。本物に無効な状態のために、@error を取っておき、回復可能な問題には @warn を、検査には @debug を。

sass
// @error stops compilation with an error message
@function divide($a, $b) {
  @if $b == 0 {
    @error "Cannot divide by zero: divide(#{$a}, #{$b})";
  }
  @return math.div($a, $b);
}

// In a mixin validating arguments
@mixin set-font-size($size) {
  @if not $size {
    @error "set-font-size requires a non-null $size, got #{$size}";
  }
  font-size: $size;
}

// @error halts the build - use for invalid inputs
// that would produce broken CSS.

meta モジュールの関数

内省を提供するのが、sass:meta です。値の型を返すのが、type-of() で、任意の値の読みやすい文字列を作るのが(デバッグに最適)、inspect()、名前による変数/mixin/関数の確認が、*-exists の関数です。呼び出し可能な参照を返すのが、meta.get-function() で、高階のパターンを可能にします。防御的なライブラリのコードに、これらを使いましょう。

sass
@use 'sass:meta';

// Inspect values
meta.type-of(10px);          // number
meta.type-of("hi");          // string
meta.type-of((a: 1));        // map
meta.inspect((a: 1, b: 2));  // (a: 1, b: 2) - readable representation

// Variable existence (within current scope)
meta.variable-exists("base");    // true if $base exists
meta.global-variable-exists("primary");

// Mixin/function existence
meta.mixin-exists("my-mixin");
meta.function-exists("my-func");

// Feature queries
meta.feature-exists("at-error");  // true

// Get a function reference (for higher-order use)
$fn: meta.get-function("lighten");

検査の関数

値のデータタイプを特定するのが、type-of() です(グローバルか meta.type-of)— 防御的な関数/mixin のロジックには不可欠です。読みやすい文字列として(マップとネストしたリストを含む)任意の Sass 値を描画するのが、inspect() で、@debug のロギングに完璧です。数値を検査するのが、math.unit()/is-unitless() です。合わせて、開発中の Sass の内部が観察可能になるのが、これらの道具です。

sass
@use 'sass:meta';
@use 'sass:math';

// type-of: get the type of any value
$value: 16px;
type-of($value);          // number
type-of("hello");         // string
type-of(#fff);            // color
type-of(true);            // bool
type-of(null);            // null
type-of(1 2 3);           // list
type-of((a: 1));          // map

// inspect: readable debug output of complex values
$map: (primary: blue, secondary: green);
debug: inspect($map);  // (primary: blue, secondary: green)

// unit / unitless for numbers
math.unit(16px);         // px
math.is-unitless(16);    // true

// Combine with @debug for tracing
@debug "got: #{inspect($map)}";
20

Sass 対 SCSS の構文

SCSS の構文(.scss)

最も人気のある Sass 構文が、SCSS(.scss)です。CSS の厳密なスーパーセットです。任意の有効な CSS ファイルが有効な SCSS であるため、.css を .scss へ改名し、漸進的に Sass の機能を加え始められます。CSS のように、波括弧とセミコロンを使うのが、SCSS です。新しいプロジェクトとチームの採用には、SCSS を。

sass
// SCSS - Sassy CSS
// Uses braces {} and semicolons ;
// Superset of CSS - all CSS is valid SCSS

$primary: #3498db;

.button {
  background: $primary;

  &:hover {
    background: darken($primary, 10%);
  }

  .icon {
    width: 16px;
    height: 16px;
  }
}

// Pros: familiar to CSS devs, easy migration, widely adopted

Sass のインデント構文(.sass)

波括弧とセミコロンを落とし、(Python や Stylus のように)インデントだけに頼るのが、Sass のインデント構文(.sass)です。より簡潔ですが、そのままの CSS を .sass ファイルへ貼り付けられず、インデントのエラーがバグの原因になります。SCSS より一般的でないですが、きれいな見た目を好む人がいます。同じ CSS へコンパイルされるのが、両方です。

sass
// Sass - indented syntax
// NO braces, NO semicolons - uses indentation only
// Removes CSS punctuation for a cleaner look

$primary: #3498db

.button
  background: $primary

  &:hover
    background: darken($primary, 10%)

  .icon
    width: 16px
    height: 16px

// Pros: less typing, cleaner visually
// Cons: can't paste CSS directly, less popular, error-prone indentation

構文間の変換

.scss と .sass の間を変換するのが、sass-convert(Sass と同梱)です。Sass 構文では、簡潔さのため、@mixin が = になり、@include が + になります。構文を超えて、同一であるのが、両方です — 同じ機能、同じ出力の CSS です。CSS の互換性とより広いツールのサポートのため、SCSS へ標準化するのが、ほとんどのチームです。

sass
// Convert SCSS to Sass (and vice versa) with the sass CLI:
// $ sass-convert style.scss style.sass
// $ sass-convert style.sass style.scss

// Bulk convert a folder:
// $ sass-convert --recursive --from scss --to sass scss/ sass/
// $ sass-convert --recursive --from sass --to scss sass/ scss/

// Key syntax differences:
// 1. SCSS uses { } and ;  |  Sass uses indentation
// 2. SCSS: @include mixin()  |  Sass: +mixin()
// 3. SCSS: @mixin name {}    |  Sass: =name
// 4. SCSS: @import "x"       |  Sass: same
// 5. Multi-line: SCSS needs ; | Sass just newlines

いつどれを使うか

より安全なデフォルトが、SCSS です。業界の標準であり、すべての CSS ファイルが有効な SCSS であり、ほとんどのドキュメント/例が、これを使うためです。句読点を嫌う開発者に訴えるのが、インデントされた .sass の構文ですが、ツールのサポートがより狭く、新しいチームメンバーのオンボーディングが難しくなります。プロジェクトごとに 1 つ選び、一貫させましょう。

sass
// Use SCSS (.scss) when:
// - Starting a new project (most common choice)
// - Migrating an existing CSS codebase (CSS is valid SCSS)
// - Working on a team (most developers know SCSS)
// - Using CSS frameworks/libraries (they're usually SCSS)

// Use Sass (.sass) when:
// - You prefer minimal punctuation / Python-like syntax
// - Writing from scratch with no CSS to migrate
// - Personal preference for cleaner-looking source

// Both produce identical CSS. The choice is stylistic.
// IMPORTANT: don't mix .scss and .sass in the same project.

よくある落とし穴

いくつかのレガシーの機能を非推奨とするのが、モダンな Sass です:除算のための / の代わりに math.div()、@import の代わりに @use/@forward、グローバルの lighten()/darken()/mix() などの代わりに sass:color/sass:math のモジュールの関数です。これらの移行を自動化するのが、sass-migrator のツールです。コードを将来対応させるため、コンパイル中の非推奨の警告を見ましょう。

sass
// 1. Division: / is deprecated for math, use math.div()
@use 'sass:math';
width: math.div(100px, 2);   // CORRECT
// width: 100px / 2;          // DEPRECATED (may be CSS list separator)

// 2. @import is deprecated - use @use/@forward
@use 'variables';             // CORRECT
// @import 'variables';        // DEPRECATED

// 3. lighten()/darken() deprecated - use color.adjust
@use 'sass:color';
color.adjust($c, $lightness: 10%);   // CORRECT
// lighten($c, 10%);                  // DEPRECATED

// 4. Global color functions deprecated - use sass:color module
color.mix(red, blue);          // CORRECT (via @use 'sass:color')
// mix(red, blue);              // DEPRECATED global function

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.