Skip to content

CSS3 チートシート

スタイリング、レイアウト、アニメーションのモジュールを持つ、CSS の最新の進化。

01

セレクタ

属性セレクタと疑似クラス

CSS3 は強力な属性セレクタと疑似クラスを導入しました。^= は接頭辞、$= は接尾辞、*= は部分文字列に一致します。nth-child で JavaScript なしにゼブラストライプ(縞模様)が実現できます。

css3
/* attribute selectors */
input[type="text"] { border: 1px solid blue; }
a[href^="https"] { color: green; }
a[href$=".pdf"] { color: red; }
a[href*="example"] { font-weight: bold; }

/* pseudo-classes */
a:visited { color: purple; }
li:first-child { font-weight: bold; }
li:nth-child(odd) { background: #f0f0f0; }
input:focus { outline: 2px solid blue; }

構造疑似クラス

構造疑似クラスは DOM での位置に基づいて要素を選択します。:first-child / :last-child が端を対象にします。nth-child(an+b) は数式をサポートします:2n は偶数、2n+1 は奇数、3n は 3 の倍数ごと。:nth-of-type は同じ要素型の兄弟だけを数えます。:empty は子を持たない要素に一致します。

css3
/* positional pseudo-classes */
li:first-child { color: green; }
li:last-child { color: red; }
li:only-child { font-weight: bold; }

/* nth variants */
li:nth-child(3) { color: blue; }
li:nth-child(2n+1) { background: #eee; } /* odd */
li:nth-last-child(2) { color: orange; }

/* type-based */
p:first-of-type { font-size: 1.2em; }
p:nth-of-type(even) { color: gray; }
div:empty { display: none; }

:is、:where、:has

:is() と :where() はセレクタを簡潔にまとめます。違いは::is() は引数の中で最も高い詳細度を取り、:where() は常に詳細度ゼロです — 上書きされやすいベーススタイルに最適。:has() は待望の親/関係セレクタで、子孫に基づいて要素をスタイルできます。

css3
/* :is() - matches any selector in the list */
:is(h1, h2, h3) { color: navy; }
:is(.btn, .link):hover { opacity: 0.8; }

/* :where() - same as :is but zero specificity */
:where(article, section) p { line-height: 1.6; }

/* :has() - parent selector (selects element that has a match) */
div:has(> img) { padding: 0; }
card:has(.badge) { border-color: gold; }
form:has(input:invalid) button { opacity: 0.5; }

否定疑似クラスとフォーム疑似クラス

:not() はセレクタを否定し、現在はリストも受け付けます。フォームの疑似クラス(:required、:valid、:invalid、:checked、:placeholder-shown、:in-range)により、JavaScript なしで入力状態に基づくスタイリングが可能です — インラインのバリデーションフィードバックやカスタム checkbox/radio スタイルに最適です。

css3
/* :not() excludes matching elements */
input:not([type="checkbox"]) { display: block; }
li:not(:last-child) { border-bottom: 1px solid #ddd; }

/* form state pseudo-classes */
input:required { border-color: red; }
input:optional { border-color: #ccc; }
input:valid { border-color: green; }
input:invalid { border-color: red; }
input:in-range { color: black; }
input:out-of-range { color: red; }
input:placeholder-shown { background: #fafafa; }
input:checked + label { font-weight: bold; }

詳細度とカスケード

セレクタが競合したとき、どのルールが適用されるかは詳細度で決まります。ID、クラス、要素を (a,b,c) として数えます。!important はカスケードを上書きしますが保守性を壊します — 避けましょう。詳細度が同点なら、ソース順で後のルールが勝ちます。DevTools は計算済みのカスケードを表示してくれます。

css3
/* specificity ranking: inline > ID > class/attr/pseudo > type/element */
#nav .item { color: red; }     /* 1,1,0 */
.menu .item { color: blue; }   /* 0,2,0 */
li.item { color: green; }      /* 0,1,1 */

/* !important overrides normal declarations */
.btn { color: white !important; }

/* source order wins on equal specificity */
.late { color: purple; }  /* wins over .early */
02

ボックスモデル

box-sizing

box-sizing: border-box は宣言した width/height の中にパディングと罫線を含めるため、サイズ計算が予測可能になります。content-box(デフォルト)はその上に加算します。border-box をグローバルに適用するのが最も重要な CSS リセットです — 最もよくあるレイアウト計算の頭痛を取り除きます。

css3
/* default: width = content only */
.box-content { box-sizing: content-box; width: 200px; padding: 20px; } /* total 240px */

/* padding & border inside width */
.box-border { box-sizing: border-box; width: 200px; padding: 20px; border: 2px solid; } /* total 200px */

/* universal reset - apply everywhere */
*, *::before, *::after {
  box-sizing: border-box;
}

マージンとパディング

パディングは罫線の内側(背景を継承)、マージンは外側(透明)です。隣接するブロック要素間の縦マージンは大きい方に相殺されます — 横マージンは決して相殺されません。margin: 0 auto は幅が定義されたブロック要素を中央寄せします。ネガティブマージンはコンテンツを引っ張れますが、控えめに使いましょう。

css3
.box {
  /* top right bottom left (clockwise) */
  margin: 10px 20px 15px 25px;
  /* 2 values: vertical horizontal */
  padding: 10px 20px;
  /* single value: all sides */
  margin: 0 auto; /* horizontal centering for fixed-width block */
}

/* margin collapse (vertical only) */
.a { margin-bottom: 30px; }
.b { margin-top: 20px; }
/* gap between .a and .b = 30px, not 50px (collapsed to larger) */

/* negative margins pull elements together */
.pull-left { margin-left: -10px; }

box-shadow

box-shadow の構文:offset-x offset-y blur-radius spread-radius color。正のオフセットは影を右/下へ押し出します。inset で内側の影になります。複数の影はレイヤー化され、最初のものが最上面です。半透明で自然な影には rgba を使います。硬い影(ぼかしゼロ)はフラットで大胆な美学を作ります。

css3
/* offset-x offset-y blur spread color */
.card { box-shadow: 0 4px 6px rgba(0,0,0,0.1); }

/* inset shadow (inside the box) */
.inset { box-shadow: inset 0 2px 4px rgba(0,0,0,0.2); }

/* multiple shadows (first = top layer) */
.layered { box-shadow: 0 1px 2px #000, 0 8px 24px rgba(0,0,0,0.15); }

/* no blur, hard shadow (neo-brutalism) */
.hard { box-shadow: 6px 6px 0 #000; }

/* glow effect */
.glow { box-shadow: 0 0 20px rgba(0,150,255,0.6); }

display の種類

display: none はレイアウトから要素を取り除きます(スペースは確保されない)。block 要素は全幅を取り縦に積み、inline 要素はテキストと共に流れ width/height を無視します。inline-block はインラインの流れとブロックのサイズ指定を組み合わせます。flow-root は clearfix ハックなしでフロートを解消します。contents はボックスを消しつつ子をレイアウトに残します。

css3
/* block: full width, new line */
div, p { display: block; }

/* inline: flows with text, ignores width/height */
span, a { display: inline; }

/* inline-block: flows inline but accepts width/height */
.tag { display: inline-block; width: 100px; }

/* none: removed from layout entirely */
.hidden { display: none; }

/* modern display values */
.flow { display: flow-root; } /* new block formatting context */
.contents { display: contents; } /* element's box disappears, children participate */

overflow

overflow はボックスを超えるコンテンツの扱いを制御します。visible(デフォルト)ははみ出させ、hidden はクリップし、auto は必要なときスクロールバーを加え、scroll は常に表示します。clip(新しい値)は hidden に似ていますが、JS によるスクロールさえ防ぎます。overflow-y/x で軸を独立に制御できます。overflow を visible 以外にすると新しい整形コンテキストが作られます。

css3
.scrollable {
  overflow: auto;       /* scrollbars when needed */
  overflow-y: scroll;   /* always show vertical scrollbar */
  overflow-x: hidden;   /* hide horizontal overflow */
}

/* visible (default) - content spills out */
.spill { overflow: visible; }

/* clip - like hidden but no programmatic scroll */
.clipped { overflow: clip; }

/* clip to a shape */
.custom-clip {
  overflow: clip;
  overflow-clip-margin: 20px;
}

/* longhand for both axes */
.both { overflow-x: hidden; overflow-y: auto; }
03

Flexbox

Flex コンテナ

display: flex で要素が flex コンテナになります。justify-content が主軸に沿って(row なら水平方向に)アイテムを整列させ、align-items が交差軸に沿って整列させます。flex-wrap でアイテムを新しい行へ折り返せます。gap がマージンベースの間隔ハックを置き換えます。Flexbox は 1 次元のレイアウト(行か列)に優れています。

css3
.container {
  display: flex;
  flex-direction: row;       /* row | row-reverse | column | column-reverse */
  justify-content: center;   /* main axis: flex-start | center | space-between | space-around | space-evenly */
  align-items: center;       /* cross axis: stretch | flex-start | center | baseline */
  flex-wrap: wrap;           /* nowrap | wrap | wrap-reverse */
  gap: 16px;                 /* spacing between items */
  align-content: space-between; /* multi-line spacing */
}

Flex アイテム

flex-grow は余ったスペースを埋める伸び方を制御します(1 = 均等配分)。flex-shrink は縮み方を、flex-basis は初期サイズを制御します。省略形 flex: 1 は basis ゼロから等しく伸びるという意味 — 等幅の列に最適です。align-self は単一のアイテムについてコンテナの align-items を上書きします。order で DOM の順を変えずに見た目上の順序を変えられます。

css3
.item {
  flex-grow: 1;     /* grow to fill extra space (0 = don't grow) */
  flex-shrink: 1;   /* shrink when space is tight (0 = don't shrink) */
  flex-basis: 200px; /* initial size before growing/shrinking */
  
  /* shorthand: flex: grow shrink basis */
  flex: 1 1 200px;   /* flexible from 200px */
  flex: 1;            /* = 1 1 0% - equal distribution */
  flex: 0 0 250px;    /* fixed width, no grow/shrink */
  
  align-self: flex-end; /* override align-items for this item */
  order: 2;             /* visual reordering (default 0) */
}

Flex 整列のパターン

Flexbox なら中央寄せは簡単です:justify-content: center + align-items: center。スティッキーフッターは、min-height: 100vh の縦 flex の body で、メインコンテンツに flex: 1 を付けます。ナビバーでは space-between が最初と最後のアイテムを反対の端へ押します。auto マージン(margin-left: auto)はアイテムを押し出す justify-content の柔軟な代替です。

css3
/* perfect centering */
.center {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

/* sticky footer: body is flex column */
body { display: flex; flex-direction: column; min-height: 100vh; }
main { flex: 1; } /* grows to fill, pushing footer down */

/* navbar: space between */
.nav { display: flex; justify-content: space-between; }

/* auto margins absorb space */
.push-right { margin-left: auto; }

Flex Wrap とレスポンシブグリッド

flex-wrap: wrap でスペースが尽きたときアイテムが新しい行へ流れます。flex: 1 1 280px は 280px で始まり行を満たすまで伸びるカードを作ります。これでメディアクエリなしのレスポンシブカードグリッドになります。注意:最終行のアイテムが伸びて満たすため不均等に見えることがあります — 一貫したカードグリッドには CSS Grid の方が適していることが多いです。

css3
.cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.card {
  /* start at 280px, grow & shrink fluidly */
  flex: 1 1 280px;
  /* prevent stretching beyond readable width */
  max-width: 100%;
}

/* OR fixed-width cards that wrap */
.card-fixed {
  flex: 0 0 300px;
}

/* last row items stretch to fill - to avoid, use grid instead */
/* gap wraps with items automatically */

Flex Direction と軸

flex-direction が主軸を決めます。row(デフォルト)では justify-content が水平方向の整列を、column では垂直方向の整列を制御します — 軸が入れ替わるのです。整列させるときは常に「主軸はどれか?」と自問しましょう。row-reverse と column-reverse はアイテムの順を反転し、justify-content によるスペース配分の仕方にも影響します。

css3
/* row: main axis = horizontal */
.row { display: flex; flex-direction: row; justify-content: center; }

/* column: main axis = vertical (axes swap!) */
.col { display: flex; flex-direction: column; align-items: center; }

/* reverse order */
.reverse { display: flex; flex-direction: row-reverse; }

/* centering in column: justify-content centers vertically */
.col-center {
  display: flex;
  flex-direction: column;
  justify-content: center; /* vertical center */
  align-items: center;     /* horizontal center */
}
04

Grid レイアウト

Grid コンテナ

display: grid で 2 次元のレイアウトを作ります。grid-template-columns が列のトラックを定義し、fr 単位が余ったスペースを比例配分します。repeat(auto-fit, minmax(200px, 1fr)) はレスポンシブグリッドの魔法のレシピです — メディアクエリなしで列が自動生成・リサイズされます。gap がトラック間のスペースをきれいに加えます。

css3
.grid {
  display: grid;
  /* fixed columns */
  grid-template-columns: 200px 1fr 200px;
  /* responsive auto columns */
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-template-rows: auto 1fr auto;
  gap: 20px;            /* row + column gap */
  row-gap: 20px;        /* gap between rows */
  column-gap: 16px;     /* gap between columns */
}

Grid テンプレートエリア

grid-template-areas では名前付き領域でレイアウトを視覚的に描けます — 非常に読みやすい。引用文字列が 1 行で、名前がアイテムを置き、ドットが空セルを示します。grid-area: name を持つアイテムがその領域を満たします。アプリシェルのようなページレベルのレイアウトを作る最も明快な方法です。

css3
.layout {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  min-height: 100vh;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }

/* empty cell with a dot */
grid-template-areas: "header header" "sidebar .";

Grid アイテムの配置

Grid アイテムは線の番号で明示的に配置できます。grid-column: 1 / 3 は 1 番線から 3 番線まで広がります(2 列分)。span キーワードはトラック数でサイズを指定します。読みやすさのため、grid-template-columns で線に名前を付けることもできます。明示的な配置がなければ、アイテムは利用可能なセルへ自動的に流れます。

css3
.item {
  /* place by line numbers: row-start / col-start / row-end / col-end */
  grid-column: 1 / 3;      /* span columns 1 to 3 */
  grid-row: 1 / 2;
  
  /* span keyword */
  grid-column: span 2;     /* span 2 columns */
  grid-row: 2 / span 3;
  
  /* shorthand: grid-area: row-start / col-start / row-end / col-end */
  grid-area: 1 / 1 / 3 / 4;
  
  /* name a line and reference it */
  grid-column-start: content-start;
}

Grid の整列

Grid の整列は 2 つのレベルで動きます。justify-content/align-content は余りがあるときコンテナ内のグリッド全体を配置し、justify-items/align-items はセル内のアイテムを整列させます(デフォルト stretch)。justify-self/align-self はアイテムごとに整列を上書きします。'justify' = インライン/主軸、'align' = ブロック/交差軸です。

css3
.grid {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  
  /* align tracks within container */
  justify-content: center;  /* center the grid horizontally */
  align-content: center;    /* center vertically (needs fixed height) */
  
  /* align items within their cells */
  justify-items: stretch;   /* fill cell width (default) */
  align-items: center;      /* center within cell height */
}

.item {
  justify-self: start;      /* override justify-items for one item */
  align-self: end;
}

auto-fit と auto-fill の違い

どちらも収まるだけのトラックを作りますが、アイテムが少ないときの振る舞いが違います。auto-fit は未使用のトラックを潰し、既存のアイテムを行いっぱいに伸ばします。auto-fill は空のトラックを保つため、アイテムは min サイズのままです。アイテムを伸ばしてスペースを埋めたいなら auto-fit、固定の一貫したアイテムサイズにしたいなら auto-fill を使います。

css3
/* auto-fit: empty tracks collapse, items stretch to fill */
.autofit {
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}

/* auto-fill: empty tracks remain, items keep their size */
.autofill {
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}

/* with few items:
   auto-fit -> items stretch to fill the row
   auto-fill -> items stay small, leaving empty columns */
05

ポジショニング

position の値

static がデフォルトです。relative は通常フローの位置からのオフセットです(スペースは保持される)。absolute はフローから外れ、最も近い配置済みの祖先(またはビューポート)を基準に配置されます。fixed はブラウザビューポートを基準です。sticky はスクロール位置に応じて relative と fixed を切り替えます — スティッキーヘッダーに最適です。

css3
/* static - default, flows normally */
.static { position: static; }

/* relative - offset from its normal position */
.relative { position: relative; top: 10px; left: 20px; }

/* absolute - positioned relative to nearest positioned ancestor */
.absolute { position: absolute; top: 0; right: 0; }

/* fixed - positioned relative to viewport (stays on scroll) */
.fixed { position: fixed; bottom: 0; left: 0; }

/* sticky - relative until scroll threshold, then fixed */
.sticky { position: sticky; top: 0; }

絶対位置での中央寄せ

絶対位置での中央寄せには複数の方法があります。translate(-50%, -50%) のトリックはどんなサイズの要素にも効きます。inset: 0 + margin: auto の手法は明示的な寸法が必要です。モダンなアプローチは display: grid と place-items: center(align-items + justify-items の省略形)— 位置計算が不要で最もシンプルな方法です。

css3
/* classic: position absolute + transform */
.center {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}

/* inset: 0 + margin: auto (needs width/height) */
.center-auto {
  position: absolute;
  inset: 0;          /* top/right/bottom/left: 0 */
  margin: auto;
  width: 300px;
  height: 200px;
}

/* modern: no positioning needed */
.center-grid { display: grid; place-items: center; }

Sticky ポジショニング

position: sticky は、しきい値(例:top: 0)に達するまで要素を通常フローに保ち、その後 fixed のように張り付きます。スティッキーヘッダーや目次のサイドバーに最適です。落とし穴:スクロール方向に overflow: hidden/auto/scroll を持つ祖先がいると、それが包含ブロックになり期待した動作が壊れます。sticky 要素には必ず背景と z-index を設定しましょう。

css3
.header {
  position: sticky;
  top: 0;            /* sticks when header hits top of viewport */
  z-index: 100;
  background: white;
}

/* sticky sidebar that scrolls with content until threshold */
.sidebar {
  position: sticky;
  top: 60px;         /* offset below the fixed header */
  max-height: calc(100vh - 60px);
  overflow-y: auto;
}

/* NOTE: a parent with overflow: hidden breaks sticky */

z-index とスタッキングコンテキスト

z-index は配置済み(static 以外)の要素でしか効きません。スタッキングコンテキストは position + z-index で作られますが、opacity < 1、transform、filter、will-change、isolation: isolate でも作られます。スタッキングコンテキスト内では子の z-index が隔離されるため、子が祖先の兄弟より上に描かれることはありません。これを理解すると z-index 軍拡競争を防げます。

css3
.modal { position: fixed; z-index: 1000; }
.overlay { position: fixed; z-index: 999; }
.card { position: relative; z-index: 1; }

/* creating a stacking context (isolates z-index) */
.context {
  position: relative;
  z-index: 0;  /* children's z-index only matters within this */
}

/* other properties that create stacking contexts:
   opacity < 1, transform, filter, will-change, isolation: isolate */
.isolated { isolation: isolate; }

inset 省略形

inset は top、right、bottom、left の論理的な省略形です — margin/padding のように 1、2、4 個の値を取れます。inset: 0 で絶対配置された要素が包含ブロックを満たすよう引き伸ばされます。4 つのプロパティを個別に宣言するよりきれいで、中央寄せには margin: auto と相性が良いです。

css3
/* inset sets top right bottom left (like margin) */
.popup {
  position: absolute;
  inset: 0;          /* all sides = 0 (stretches to fill parent) */
}

/* two values: vertical horizontal */
.pill {
  position: absolute;
  inset: 10px 20px;  /* top/bottom 10px, left/right 20px */
}

/* four values: top right bottom left */
.box {
  position: absolute;
  inset: 10px 20px 30px 40px;
}

/* longhand equivalents */
.inset-longhand {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}
06

テキストのスタイリング

フォントプロパティ

font-family は最後に必ず総称ファミリー(serif、sans-serif、monospace)を最終フォールバックとして置きましょう。font-weight は 100〜900 の範囲で、一般的なのは 400(normal)と 700(bold)です。line-height は単位なし(1.5)にするのが最良で、font-size に合わせて拡大します。font の省略形は size と family が必須で、順序は style、weight、size/line-height、family です。

css3
body {
  font-family: "Helvetica Neue", Arial, sans-serif; /* fallback chain */
  font-size: 16px;
  font-weight: 400;     /* 100-900; 400=normal, 700=bold */
  font-style: italic;   /* normal | italic | oblique */
  line-height: 1.5;     /* unitless = multiplier of font-size */
  letter-spacing: 0.5px;
  word-spacing: 2px;
  font-variant: small-caps;
}

/* shorthand: style weight size/line-height family (order matters) */
p { font: italic 700 16px/1.5 "Georgia", serif; }

テキストの整形

text-align: justify は白い川(隙間の筋)を作ることがあります — きれいなブロックには hyphens: auto と組み合わせましょう。text-decoration は現在 line、style、color を 1 つの省略形で受け付けます。text-transform: capitalize は各単語をタイトルケースにします。white-space: nowrap で折り返しを防止し、text-shadow は offset-x offset-y blur color を取ります。

css3
.text {
  text-align: justify;          /* left | right | center | justify */
  text-decoration: underline wavy red; /* line style color */
  text-decoration: line-through;
  text-transform: uppercase;    /* lowercase | capitalize */
  text-indent: 2em;             /* first-line indent */
  white-space: nowrap;          /* prevent wrapping */
  word-break: break-word;       /* break long words */
  hyphens: auto;                /* auto-hyphenate (needs lang attr) */
  text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}

テキストのはみ出しと省略記号

1 行での切り詰めには 3 つのプロパティが必要です:white-space: nowrap、overflow: hidden、text-overflow: ellipsis。複数行の切り詰めには -webkit-line-clamp と display: -webkit-box を使います(まだ -webkit- 接頭辞が必要ですが、モダンブラウザすべてで動きます)。切り詰めが発動するには max-width か width が必要です。

css3
.truncate {
  /* three properties required for ellipsis */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;    /* clip | ellipsis */
  max-width: 200px;
}

/* multi-line clamp (line-clamp) */
.clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3;       /* limit to 3 lines */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* custom fade effect */
.fade {
  -webkit-mask-image: linear-gradient(to bottom, black 70%, transparent);
}

text-shadow とエフェクト

text-shadow は offset-x offset-y blur-radius color を取ります。複数の影はレイヤー化され最初のものが最上面です — ネオンのグロー、テキストの輪郭(4 方向の影で輪郭を模倣)に有用です。-webkit-text-stroke と違い、text-shadow はすべての環境でサポートされています。ぼかしなしの硬い影はレトロでシール風の美学を作ります。

css3
/* x-offset y-offset blur color */
.shadow { text-shadow: 2px 2px 4px rgba(0,0,0,0.3); }

/* multiple shadows (first = top) */
.neon { text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #0ff; }

/* 3D letterpress effect */
.letterpress { text-shadow: 0 1px 0 rgba(255,255,255,0.5); }

/* outline text (no blur, light color) */
.outline { text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; }

/* hard shadow retro effect */
.retro { text-shadow: 4px 4px 0 #ff6b6b; }

書字方向と direction

writing-mode はテキストの方向を制御します:horizontal-tb(デフォルト)、vertical-rl(伝統的な中国語/日本語など)、vertical-lr。direction: rtl はアラビア語のような右から左の言語を扱います。論理プロパティ(margin-inline-start、padding-block、inset-inline-end)は書字モードと方向に自動で適応するため、真に国際化された方向非依存のレイアウトに不可欠です。

css3
/* horizontal (default) */
.horizontal { writing-mode: horizontal-tb; }

/* vertical, top to bottom */
.vertical-rl { writing-mode: vertical-rl; }
.vertical-lr { writing-mode: vertical-lr; }

/* text direction */
.rtl { direction: rtl; unicode-bidi: bidi-override; }

/* logical properties adapt to writing mode */
.box {
  margin-inline-start: 10px;   /* logical left in LTR */
  padding-block: 20px;         /* logical top/bottom */
  inset-inline-end: 0;         /* logical right in LTR */
}
07

背景とグラデーション

background 省略形

background 省略形はすべての背景プロパティを受け付けます。position と size を一緒に使うときはスラッシュで区切ります(center/cover)。複数の背景はカンマ区切りでレイヤー化され、先に宣言されたものが最上面です。単色は必ず最後にフォールバックとして置きましょう。ボックスを満たすには cover、画像全体を収めるには contain です。

css3
.box {
  /* longhand */
  background-color: #fff;
  background-image: url("bg.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-attachment: fixed;
  
  /* shorthand (color image position/size repeat attachment) */
  background: #fff url("bg.png") center/cover no-repeat fixed;
}

/* multiple backgrounds (first = top layer) */
.multi {
  background: url("top.png") top left/contain no-repeat,
              url("bottom.png") bottom right/cover no-repeat #eee;
}

リニアグラデーション

linear-gradient(direction, color-stops) は滑らかな遷移を作ります。方向はキーワード(to right)か角度(45deg)です。stop にはパーセンテージの位置を含められます — 同じ位置に 2 つの stop を置くとハードな境目ができます(縞模様に最適)。グラデーションは画像なので background-image に置き、画像が受け付けられる場所ならどこでも使えます。

css3
/* direction or angle, then color stops */
.gradient { background: linear-gradient(to right, red, blue); }
.gradient-45 { background: linear-gradient(45deg, red, blue); }

/* multiple color stops */
.rainbow { background: linear-gradient(to right, red, orange, yellow, green, blue); }

/* color stops with positions */
.hard-stop { background: linear-gradient(to right, red 0%, red 50%, blue 50%, blue 100%); }

/* transparent stops for fade effects */
.fade { background: linear-gradient(to bottom, rgba(0,0,0,0.5), transparent); }

ラジアルとコニカルグラデーション

radial-gradient は中心点から外へ放射します — スポットライトやボタンに有用です。中心を配置でき(at top left)、形状/サイズを制御できます(circle、closest-side)。conic-gradient は点の周りで色を回転させます — 円グラフやカラーホイールに最適です。コニカルグラデーションのハードな stop できれいな円のスライスが作れます。

css3
/* radial: radiates from a center point */
.radial { background: radial-gradient(circle, red, blue); }
.radial-c { background: radial-gradient(circle at top left, #fff, #000); }
.radial-size { background: radial-gradient(closest-side, red, blue); }

/* conic: rotates around a center point */
.pie { background: conic-gradient(red 0% 30%, blue 30% 70%, green 70% 100%); }

/* conic with angle start */
.spin { background: conic-gradient(from 45deg, red, yellow, green, red); }

background-clip と origin

background-clip は背景がどこまで広がるかを制御します:border-box(デフォルト、罫線の下まで)、padding-box(罫線の内側)、content-box(パディングの内側)。見出しのトリック:background-clip: text と color: transparent で、テキストをグラデーションや画像で満たせます。Safari のため必ず -webkit- 接頭辞版も含めましょう。background-origin が位置決め領域を設定します。

css3
/* clip: where the background paints */
.border-box { background-clip: border-box; } /* default - under border */
.padding-box { background-clip: padding-box; } /* inside border */
.content-box { background-clip: content-box; } /* inside padding */

/* text clip: gradient-filled text */
.gradient-text {
  background: linear-gradient(to right, red, blue);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  -webkit-text-fill-color: transparent;
}

/* origin: where positioning starts */
.origin { background-origin: content-box; }

背景の固定とパララックス

background-attachment: fixed はパララックス効果を作ります — 背景が固定され、コンテンツがその上をスクロールします。scroll(デフォルト)は要素と共に動き、local は要素のコンテンツと共にスクロールします(スクロール可能なボックスに有用)。fixed の attachment はモバイルでカクつきサポートも不十分です。本番のパララックスには、スクロール位置に基づく transform: translate3d を代わりに使いましょう。

css3
/* fixed: background stays put during scroll (parallax) */
.parallax {
  background-image: url("hero.jpg");
  background-attachment: fixed;
  background-size: cover;
  height: 100vh;
}

/* scroll: scrolls with element (default) */
.scroll { background-attachment: scroll; }

/* local: scrolls with element's content */
.local {
  background-attachment: local; /* scrolls with inner content */
}

/* NOTE: background-attachment: fixed has poor mobile support
   prefer transform-based parallax for mobile */
08

罫線と角丸

border-radius

border-radius は角を丸めます(左上から時計回りに 1〜4 個の値)。スラッシュは楕円の角のための水平/垂直半径を分けます。正方形に border-radius: 50% で完全な円になり、長方形では楕円になります。個別指定(border-top-left-radius)で各角を制御できます。角丸は背景、罫線、(overflow: hidden があれば)子のコンテンツをクリップします。

css3
.box { border-radius: 10px; }              /* all corners */
.box-2 { border-radius: 10px 20px; }        /* top-left/bottom-right  top-right/bottom-left */
.box-4 { border-radius: 10px 20px 30px 40px; } /* TL TR BR BL (clockwise) */

/* per-corner longhand */
.card {
  border-top-left-radius: 10px;
  border-top-right-radius: 20px;
  border-bottom-right-radius: 30px;
  border-bottom-left-radius: 40px;
}

/* elliptical corners (horizontal / vertical) */
.ellipse { border-radius: 50px / 25px; }

/* perfect circle (square element) */
.circle { border-radius: 50%; }

border-image

border-image は画像を 9 領域にスライスし、角/縁を罫線に適用します。border-image-slice が元画像を分割し、repeat が縁の敷き詰め方を制御します。モダンなトリック:border-image を linear-gradient と slice 1 で使い、グラデーションの罫線を作ります。注意:border-image は border-style を置き換えるため、先に border-width を設定してください。

css3
.frame {
  border: 20px solid transparent;
  border-image-source: url("frame.png");
  border-image-slice: 30;        /* slice image into 9 regions */
  border-image-width: 20px;
  border-image-outset: 0;
  border-image-repeat: stretch;  /* stretch | repeat | round | space */
}

/* shorthand */
.frame-shorthand {
  border: 20px solid transparent;
  border-image: url("frame.png") 30 stretch;
}

/* gradient border (using border-image) */
.grad-border {
  border: 4px solid;
  border-image: linear-gradient(to right, red, blue) 1;
}

複数の罫線

CSS は複数の border プロパティを重ねられませんが、回避策があります。オフセットと spread がゼロの box-shadow はくっきりした外側の罫線を作ります(border-radius とも併用可)。outline は外側に 2 本目の罫線を引きますが border-radius を無視します。疑似要素なら角丸も含めて完全に制御できます。各手法にトレードオフがあるため、角丸が必要かどうかで選びましょう。

css3
/* technique 1: box-shadow (no rounded issue) */
.multi-shadow {
  box-shadow: 0 0 0 5px red, 0 0 0 10px blue;
}

/* technique 2: outline (outside border, no radius) */
.outline-border {
  border: 5px solid red;
  outline: 5px solid blue;
  outline-offset: 0;
}

/* technique 3: pseudo-element (full control) */
.pseudo-border {
  position: relative;
  border: 5px solid red;
}
.pseudo-border::after {
  content: "";
  position: absolute;
  inset: -10px;
  border: 5px solid blue;
  border-radius: inherit;
}

グラデーションの罫線

グラデーションの罫線は厄介です — border-image は border-radius に対応しないためです。堅牢な解決策は、2 つの背景をレイヤーすることです — padding-box にクリップされた単色と border-box にクリップされたグラデーションを、透明な罫線と共に重ねます。これなら border-radius を尊重し、どこでも動きます。角丸が不要なら、よりシンプルな border-image の方法で構いません。

css3
/* method 1: border-image (works but no border-radius) */
.grad-1 {
  border: 4px solid;
  border-image: linear-gradient(to right, red, blue) 1;
}

/* method 2: background-clip trick (works with radius) */
.grad-2 {
  border: 4px solid transparent;
  border-radius: 12px;
  background:
    linear-gradient(white, white) padding-box,
    linear-gradient(to right, red, blue) border-box;
}

/* method 3: mask + pseudo (advanced, supports radius + animation) */

Outline とフォーカススタイル

outline は罫線の外側に描かれレイアウトに影響しないため、フォーカスインジケーターに最適です。outline-offset が隙間を加えます。重要なアクセシビリティルール:目に見える代替なしに outline: none を設定してはいけません。:focus-visible はキーボード操作(マウスクリックではない)のときだけ輪郭を表示します — モダンでユーザーフレンドリーなフォーカススタイリングです。

css3
/* outline: doesn't affect layout, draws outside border */
.focusable:focus {
  outline: 2px solid blue;
  outline-offset: 2px;  /* gap between element and outline */
}

/* never use outline: none without a replacement */
button:focus { outline: none; box-shadow: 0 0 0 3px rgba(0,150,255,0.5); }

/* :focus-visible: only shows outline for keyboard users */
button:focus-visible { outline: 2px solid blue; outline-offset: 2px; }
button:focus:not(:focus-visible) { outline: none; }

/* outline shorthand */
.box { outline: 2px dashed red; }
09

Transform

2D Transform

2D transform — translate、rotate、scale、skew — はレイアウトに影響せず要素を動かし歪めます(兄弟は再フローしません)。複合 transform は右から左へ適用されるため順序が重要です:translate の前に rotate すると回転した軸に沿って動きます。transform は reflow を引き起こさないためアニメーションに最適で、GPU で高速化されます。

css3
.box { transform: translate(50px, 20px); }   /* move right 50, down 20 */
.box-x { transform: translateX(50px); }
.box-scale { transform: scale(1.5); }          /* grow 1.5x */
.box-scale-2 { transform: scale(1, 2); }       /* x 1, y 2 */
.box-rotate { transform: rotate(45deg); }      /* clockwise */
.box-skew { transform: skew(20deg, 10deg); }   /* skew x, y */

/* combine transforms (order matters!) */
.combo { transform: translate(20px, 0) rotate(45deg) scale(1.2); }

/* transform does NOT affect layout (no reflow) */

transform-origin

transform-origin は transform の支点を設定します — デフォルトは要素の中心です。キーワード(top left)、ピクセル、パーセンテージを受け付けます。原点を変えると回転と拡大縮小の挙動が劇的に変わります:上の縁の周りで裏返すカードには transform-origin: top が必要です。3D transform では第 3 の z 軸の値も指定できます。

css3
.box { transform: rotate(45deg); }

/* default origin: center center (50% 50%) */
.center { transform-origin: center center; }

/* rotate around top-left corner */
.tl { transform-origin: top left; transform: rotate(45deg); }

/* custom point (x y) */
.custom { transform-origin: 20px 50px; transform: rotate(45deg); }

/* 3-value form (x y z) */
.three-d { transform-origin: 0 0 100px; }

/* percentage-based */
.pct { transform-origin: 100% 0; } /* top-right corner */

3D Transform

3D transform は rotateX、rotateY、rotateZ、translateZ、scaleZ を加えます。perspective(n) は奥行きを有効にするため最初の transform 関数として(または親に)適用する必要があります — 小さい値ほど 3D 効果が誇張されます。translate3d と scale3d は GPU で高速化され、アニメーションでは 2D の対応物より良いパフォーマンスを示します。

css3
.card { transform: perspective(1000px) rotateY(45deg); }

/* rotateX/Y/Z - rotate around 3D axes */
.flip { transform: rotateX(180deg); }   /* flip horizontally */
.turn { transform: rotateY(180deg); }   /* flip like a page */
.spin { transform: rotateZ(90deg); }    /* same as rotate() */

/* translate3d (GPU-accelerated) */
.move { transform: translate3d(50px, 20px, 100px); }

/* scale3d */
.grow { transform: scale3d(1.5, 1.5, 1.5); }

/* combined 3D */
.combo-3d { transform: perspective(800px) rotateX(15deg) rotateY(-20deg) translateZ(-50px); }

Perspective と 3D 空間

perspective は視点との距離を定義します — 小さいほど 3D が劇的です。親に置けばすべての子が同じ消失点を共有します。transform-style: preserve-3d はネストした要素を共有の 3D 空間に置きます(立方体の構築に不可欠)。backface-visibility: hidden は要素の裏面を隠します — フリップカード効果の鍵です。

css3
/* perspective on parent: applies to all children uniformly */
.scene { perspective: 1000px; }
.cube { transform: rotateY(45deg); }

/* perspective() in transform: only affects that element */
.solo { transform: perspective(1000px) rotateY(45deg); }

/* perspective-origin: vanishing point */
.scene { perspective: 1000px; perspective-origin: top left; }

/* transform-style: preserve-3d lets children share 3D space */
.cube {
  transform-style: preserve-3d;
  transform: rotateY(30deg);
}
.cube .face { position: absolute; transform: translateZ(50px); }

/* backface-visibility: hide back of flipped element */
.card { backface-visibility: hidden; }

Transform のアニメーション(パフォーマンス)

アニメーションさせるのは常に transform と opacity にしましょう — GPU で高速化され、レイアウト(reflow)や描画をトリガーしません。top/left/width/margin のアニメーションは毎フレームでブラウザにレイアウト再計算を強制し、カクつきの原因になります。will-change: transform はブラウザにコンポジターレイヤーの事前準備を促しますが、乱用はメモリを浪費します。アニメーションの直前に適用し、後に取り除きましょう。

css3
/* GOOD: animate transform & opacity (GPU-accelerated) */
.smooth {
  transition: transform 0.3s ease;
}
.smooth:hover { transform: translateY(-5px); }

/* BAD: animating top/left triggers reflow */
.janky { transition: top 0.3s; }
.janky:hover { top: -5px; }

/* will-change: hint the browser to optimize */
.prepared {
  will-change: transform;  /* prepare for upcoming transform changes */
}

/* force GPU layer (use sparingly) */
.gpu { transform: translateZ(0); }
10

Transition

transition 省略形

transition は property duration timing-function delay の順です。デフォルトは all 0s ease 0s なので、transition: 0.3s と書くだけで変化するすべてのプロパティがアニメーションします。パフォーマンスと制御のため、具体的なプロパティを列挙しましょう。複数の transition はカンマ区切りです。transition は要素のデフォルト状態に置きます(:hover ではなく)— そうすれば逆方向のアニメーションも再生されます。

css3
.btn {
  background: blue;
  /* shorthand: property duration timing-function delay */
  transition: background 0.3s ease 0s;
  
  /* common usage */
  transition: all 0.3s ease;
  
  /* multiple properties (comma-separated) */
  transition: background 0.3s, transform 0.2s ease-out;
  
  /* list the same duration on many properties */
  transition: 0.3s;
}

.btn:hover {
  background: darkblue;
  transform: scale(1.05);
}

タイミング関数

タイミング関数は加速を制御します。ease(デフォルト)は滑らかです。ease-out は UI で最もレスポンシブに感じられます(速く始まりゆっくり終わる)。linear は多くの動きで不自然に感じられます。cubic-bezier(x1,y1,x2,y2) でカスタム曲線を作れ — y 軸で 0〜1 の外の値は行き過ぎ/バウンスを作ります。steps(n) は離散的な跳びを作り、スプライトシートのアニメーションに有用です。

css3
.ease { transition: all 0.3s ease; }              /* default, smooth start/end */
.linear { transition: all 0.3s linear; }          /* constant speed */
.ease-in { transition: all 0.3s ease-in; }        /* slow start */
.ease-out { transition: all 0.3s ease-out; }      /* slow end (feels responsive) */
.ease-in-out { transition: all 0.3s ease-in-out; }/* slow both ends */

/* cubic-bezier: custom curve (P1x P1y P2x P2y) */
.custom { transition: all 0.3s cubic-bezier(0.68, -0.55, 0.27, 1.55); } /* overshoot */

/* steps: jump in increments */
.steps { transition: all 0.3s steps(4, end); }

複数と段階的な transition

プロパティごとに異なる時間と遅延を設定できます — あるプロパティが終わってから別が始まるような演出に有用です。transition-delay はリストの段階的な登場を作り、nth-child と組み合わせれば各アイテムを順に遅延させられます。遅延は退場にも使えますが注意:遅延の途中でユーザーがホバーを外すと、登場が急に飛ぶことがあります。

css3
.card {
  /* different durations per property */
  transition: transform 0.2s ease-out, box-shadow 0.4s ease;
  
  /* delay creates staggered effect */
  transition: background 0.3s, color 0.3s 0.1s; /* color starts after 0.1s */
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
  background: #f5f5f5;
}

/* stagger multiple elements via transition-delay */
.item:nth-child(1) { transition-delay: 0s; }
.item:nth-child(2) { transition-delay: 0.1s; }
.item:nth-child(3) { transition-delay: 0.2s; }

transition 可能なプロパティ

滑らかに遷移するプロパティと、カクつきを生むプロパティがあります。GPU で高速化されるスターは transform、opacity、filter です。色と box-shadow は問題ありません(レイアウトではなく描画をトリガーする)。width、height、margin、top、left の遷移は避けましょう — 毎フレームでレイアウトの再計算を強制します。サイズ変更のアニメーションには transform: scale() を使いましょう。

css3
/* WELL-SUPPORTED & performant */
.good {
  transition: transform 0.3s, opacity 0.3s, filter 0.3s;
}

/* OK but may trigger paint */
.okay {
  transition: background-color 0.3s, color 0.3s, border-color 0.3s;
  transition: box-shadow 0.3s;
}

/* AVOID: triggers layout (reflow) - janky */
.bad {
  transition: width 0.3s, height 0.3s, margin 0.3s, top 0.3s, left 0.3s;
}

/* if you must animate size, use transform: scale() instead */
.smooth-resize { transition: transform 0.3s; }

Transition のトリガー

transition はプロパティが変わるたびに発火します:疑似クラスの状態(:hover、:focus、:checked)、クラスの変更(JS が追加/削除)、メディアクエリの変化。新旧の値の間を滑らかに補間します。transition は新しい状態へ向かうときだけ動くのではなく、両方向(in/out)でアニメーションします。より複雑で、ループする、あるいは多段階の動きには @keyframes アニメーションを使いましょう。

css3
/* hover trigger */
.btn { transition: all 0.3s; }
.btn:hover { transform: scale(1.1); }

/* focus trigger (accessibility-friendly) */
.input { transition: border-color 0.2s; }
.input:focus { border-color: blue; }

/* class change via JavaScript */
.modal { transition: opacity 0.3s; opacity: 0; }
.modal.open { opacity: 1; }

/* media query trigger */
.box { transition: width 0.3s; width: 100%; }
@media (min-width: 768px) { .box { width: 50%; } }

/* CSS state triggers (:checked) */
.toggle:checked + .menu { transition: max-height 0.3s; max-height: 500px; }
11

アニメーション

@keyframes

@keyframes はアニメーションのシーケンスを定義します。stop はパーセンテージ(0%、50%、100%)か from/to(0%/100% と等価)です。stop に書かれていないプロパティは定義された stop の間で補間されます。アニメーション可能なプロパティ(transform、opacity、色)だけが機能します — display、position などは不可です。@keyframes は 1 回定義すれば多くの要素で再利用できます。

css3
@keyframes bounce {
  0%   { transform: translateY(0); }
  50%  { transform: translateY(-30px); }
  100% { transform: translateY(0); }
}

/* from/to shorthand (2-stop) */
@keyframes fadeIn {
  from { opacity: 0; }
  to   { opacity: 1; }
}

/* multiple properties at each stop */
@keyframes pulse {
  0%   { opacity: 1; transform: scale(1); }
  50%  { opacity: 0.5; transform: scale(1.1); }
  100% { opacity: 1; transform: scale(1); }
}

animation 省略形

animation 省略形は 8 つのプロパティをこの順で詰めます:name duration timing-function delay iteration-count direction fill-mode play-state。最低でも name と duration が必要です。注意:時間の値は曖昧さを持ちます — 最初の時間が duration、2 番目が delay です。本番での読みやすさには、個別指定か部分的な省略形を推奨します。

css3
.bouncing {
  /* longhand */
  animation-name: bounce;
  animation-duration: 1s;
  animation-timing-function: ease-in-out;
  animation-delay: 0s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-fill-mode: both;
  animation-play-state: running;
  
  /* shorthand: name duration timing delay count direction fill-mode play-state */
  animation: bounce 1s ease-in-out 0s infinite alternate both running;
  
  /* minimal: name + duration */
  animation: bounce 1s;
}

反復と方向

animation-iteration-count が繰り返しを制御します — infinite は永遠にループし、小数値は部分的なサイクルを再生します。animation-direction: alternate はアニメーションを順再生した後、次のイテレーションで逆再生し、シームレスなバウンスを作ります。reverse は逆再生し、alternate-reverse は逆から始めます。脈動や呼吸効果のようなピンポン動作には alternate が不可欠です。

css3
/* iteration-count: how many times to play */
.once { animation-iteration-count: 1; }    /* default */
.thrice { animation-iteration-count: 3; }
.forever { animation-iteration-count: infinite; }
.fractional { animation-iteration-count: 0.5; } /* half a play */

/* direction */
.normal { animation-direction: normal; }       /* 0% -> 100% */
.reverse { animation-direction: reverse; }     /* 100% -> 0% */
.alternate { animation-direction: alternate; } /* forward, then backward */
.alternate-rev { animation-direction: alternate-reverse; }

animation-fill-mode

animation-fill-mode はアニメーション実行前後のスタイルを制御します。none(デフォルト)は要素の通常スタイルへ戻ります。forwards は終了後、最後のキーフレームの状態を保ちます — 登場アニメーションには不可欠で、要素が元に戻る(スナップバック)のを防ぎます。backwards は遅延中、最初のキーフレームを適用します。both は両方をカバーします。1 回限りの登場には forwards か both を。

css3
@keyframes slideIn {
  from { transform: translateX(-100%); }
  to   { transform: translateX(0); }
}

/* none (default): reverts to original styles before/after */
.none { animation: slideIn 1s; }

/* forwards: holds the final (to) state after finishing */
.forwards { animation: slideIn 1s forwards; }

/* backwards: applies the (from) state during delay */
.backwards { animation: slideIn 1s 0.5s backwards; }

/* both: applies from during delay AND holds to after */
.both { animation: slideIn 1s 0.5s both; }

play-state と一時停止

animation-play-state: paused はアニメーションを現在のフレームで凍結し、running で再開します。ホバー時や JS でトグルするクラスで一時停止する最もきれいな方法です — アニメーションは再開ではなく位置を記憶します。パフォーマンスのため、画面外へスクロールした要素のアニメーションは IntersectionObserver で一時停止しましょう。アクセシビリティのため reduced-motion メディアクエリと組み合わせます。

css3
.anim { animation: spin 2s linear infinite; }

/* pause on hover */
.anim:hover { animation-play-state: paused; }

/* pause via class (JS toggle) */
.anim.paused { animation-play-state: paused; }

/* useful for performance: pause off-screen animations */
.offscreen { animation-play-state: paused; }

/* resume */
.resumed { animation-play-state: running; }
12

メディアクエリ

基本の構文

メディアクエリは条件付きでスタイルを適用します。(min-width: 768px) はモバイルファースト — 768px 以上の画面に適用します。and(両方一致)、カンマ(OR)、not(否定)で組み合わせます。モバイルファーストのアプローチ(min-width)が推奨です:小さい画面向けの基本スタイルを書き、大きな画面向けに拡張します。これで小画面の CSS が軽く保たれます。

css3
/* apply styles when viewport is at least 768px wide */
@media (min-width: 768px) {
  .grid { grid-template-columns: repeat(2, 1fr); }
}

/* combine conditions with and */
@media (min-width: 768px) and (max-width: 1024px) {
  .box { padding: 20px; }
}

/* list of queries (OR) */
@media (max-width: 600px), (min-width: 1200px) {
  .text { font-size: 14px; }
}

/* negate with not */
@media not print {
  .screen-only { display: block; }
}

min/max 幅のブレークポイント

ブレークポイントは特定のデバイスではなくコンテンツに基づくべきですが、一般的な範囲がうまく機能します:640px(タブレット)、1024px(デスクトップ)、1280px(大型)。モバイルファーストとは min-width を使い、モバイル用スタイルを基本として書くことです。新しい範囲構文(width >= 768px)は読みやすく、モダンブラウザすべてでサポートされ、冗長な min/max の組み合わせを置き換えます。

css3
/* common breakpoints (mobile-first) */
/* base styles (mobile) */
.container { padding: 16px; }

@media (min-width: 640px)  { /* small tablets */ 
  .container { padding: 24px; }
}
@media (min-width: 1024px) { /* desktops */
  .container { padding: 32px; max-width: 1200px; margin: 0 auto; }
}
@media (min-width: 1280px) { /* large screens */
  .container { max-width: 1400px; }
}

/* range syntax (newer, cleaner) */
@media (width >= 768px) and (width <= 1024px) {
  .box { padding: 20px; }
}

向きとアスペクト比

幅の他、メディアクエリは向き(portrait/landscape)、aspect-ratio、ホバー能力、ポインタタイプを対象にできます。@media (hover: hover) はホバースタイルを実際のポインタを持つデバイスだけに適用させます(タッチでの張り付きホバーを回避)。(pointer: coarse) はタッチデバイスを対象にします — タップターゲットの拡大に最適です。これらの機能で真にデバイスに適したインターフェースが実現します。

css3
/* portrait vs landscape */
@media (orientation: portrait) {
  .grid { grid-template-columns: 1fr; }
}
@media (orientation: landscape) {
  .grid { grid-template-columns: 1fr 1fr; }
}

/* aspect ratio */
@media (min-aspect-ratio: 16/9) {
  .video { width: 100%; height: auto; }
}

/* hover capability: devices that support hover */
@media (hover: hover) {
  .btn:hover { background: darkblue; }
}

/* pointer: fine (mouse) vs coarse (touch) */
@media (pointer: coarse) {
  .btn { padding: 16px 32px; } /* bigger tap targets */
}

印刷スタイル

print メディアクエリはページの印刷時の見た目を整形します。ナビゲーション、広告、インタラクティブ要素を隠し、コンテンツを全幅に広げ、インク効率のために黒白を強制しましょう。break-inside: avoid で要素がページをまたいで分割されるのを防ぎ、break-before: page で改ページを強制します。リンクへの ::after のトリックで印刷時に URL が現れます — 印刷可能な記事には非常に有用です。

css3
@media print {
  /* hide non-essential UI */
  .nav, .sidebar, .ads, .comments { display: none; }
  
  /* expand main content */
  .main { width: 100%; margin: 0; }
  
  /* force black text on white */
  body { color: black; background: white; }
  
  /* avoid breaking inside elements */
  h1, h2, img, table { break-inside: avoid; }
  
  /* page breaks before sections */
  h1 { break-before: page; }
  
  /* show URLs after links */
  a[href]::after { content: " (" attr(href) ")"; }
}

prefers-reduced-motion と color-scheme

prefers-reduced-motion は重要なアクセシビリティ機能です — 前庭障害を持つユーザーは動きを最小限にする必要があります。アニメーションを無効化または短縮するモーション低減のフォールバックを必ず提供しましょう。prefers-color-scheme でユーザーの OS テーマに自動適応できます。ダークモードでは、ダーク背景上で機能するコントラスト、画像、シャドウも考慮しましょう。

css3
/* respect users who prefer less motion */
@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }
}

/* light/dark mode */
@media (prefers-color-scheme: dark) {
  body { background: #1a1a1a; color: #eee; }
  .card { background: #2a2a2a; }
}

@media (prefers-color-scheme: light) {
  body { background: white; color: #333; }
}
13

レスポンシブデザイン

clamp() による流動的なタイポグラフィ

clamp(min, preferred, max) は境界の間を流動的に拡縮する値を作ります — メディアクエリなしで適応するタイポグラフィやスペーシングに最適です。preferred 値は通常 vw ベースの式です。これで多くのブレークポイントが不要になります。アクセシビリティのため rem と組み合わせましょう(ユーザーはルートのフォントサイズを拡大できます)。流動的な type はデバイス間の体感パフォーマンスと読みやすさを向上させます。

css3
/* clamp(min, preferred, max) - fluid between bounds */
h1 {
  /* scales from 1.5rem to 3rem as viewport grows */
  font-size: clamp(1.5rem, 5vw, 3rem);
}

p {
  /* readable body text on any screen */
  font-size: clamp(1rem, 2.5vw, 1.25rem);
}

/* fluid spacing */
.section {
  padding: clamp(1rem, 4vw, 3rem);
}

/* fluid container width */
.container {
  width: clamp(280px, 90vw, 1200px);
  margin: 0 auto;
}

モバイルファーストのアプローチ

モバイルファーストとは、小さい画面向けのスタイルを基本として書き、min-width メディアクエリで大きな画面向けに拡張することです。これで CSS が軽くなり(モバイルは必要なものだけをダウンロードする)、コンテンツ優先の考え方を強制します。デスクトップファースト(max-width)ではモバイルがデスクトップ用スタイルをダウンロードして上書きする必要があり — 遅く保守も難しくなります。

css3
/* base = mobile styles (no media query) */
.card {
  width: 100%;
  padding: 12px;
  font-size: 14px;
}

/* progressively enhance for larger screens */
@media (min-width: 640px) {
  .card { width: 50%; padding: 16px; }
}

@media (min-width: 1024px) {
  .card { width: 33.33%; padding: 24px; font-size: 16px; }
}

/* AVOID desktop-first (forces mobile to override) */
/* @media (max-width: 640px) { ... } */

コンテナクエリ

コンテナクエリはゲームチェンジャーです:コンポーネントがビューポートではなく親のサイズに反応できます。カードが狭いサイドバーにいても広いメインエリアにいてもレイアウトを適応させられます — 真のコンポーネントレベルのレスポンシブ性です。container-type: inline-size が幅をクエリします(最も高性能)。コンテナに名前を付けて特定のものを対象にするか、名前なしで最も近い祖先を対象にしましょう。

css3
/* make an element a query container */
.sidebar {
  container-type: inline-size;
  container-name: sidebar;
}

/* styles based on the container's size, not the viewport */
@container sidebar (min-width: 400px) {
  .card {
    grid-template-columns: 1fr 1fr;
  }
}

/* inline-size = width only (most common, performant) */
/* size = both dimensions (more expensive) */

/* unnamed container query (uses nearest ancestor) */
.card-wrap { container-type: inline-size; }
@container (min-width: 500px) {
  .card { flex-direction: row; }
}

ビューポート単位

vh/vw はビューポートのパーセンテージです。問題:モバイルの 100vh はアドレスバーの表示/非表示で変化し、カクつきの原因になります。新しい svh/lvh/dvh 単位がこれを解決します — dvh は動的に更新し、svh は最も小さい安定値を使います。vmin/vmax は小さい方/大きい方のビューポート寸法です — 拡縮する正方形の要素に最適。vw のフォントサイズには calc や clamp で rem/px の下限を必ず付けましょう。

css3
.hero {
  height: 100vh;        /* full viewport height */
  /* small viewport units: account for mobile browser chrome */
  height: 100svh;       /* smallest possible viewport (stable) */
  height: 100lvh;       /* largest possible viewport */
  height: 100dvh;       /* dynamic - updates as chrome shows/hides */
}

.full-width { width: 100vw; }
.responsive-font { font-size: 5vw; }

/* vmin/vmax: smaller/larger of width or height */
.square { width: 50vmin; height: 50vmin; }
.banner { height: 30vmax; }

/* combining with calc for safety */
.hero-text { font-size: calc(16px + 2vw); }

aspect-ratio

aspect-ratio は幅:高さの比を自動的に保ちます — レスポンシブ動画のための padding-top ハックはもう不要です。要素の高さは幅から(またはその逆から)導かれます。画像に object-fit: cover を組み合わせると、画像の読み込み中のレイアウトシフトを防げます。メディア用のスペース確保と累積レイアウトシフト(CLS — Core Web Vital の一つ)の回避のための最もきれいな方法です。

css3
/* maintain a 16:9 ratio regardless of width */
.video {
  aspect-ratio: 16 / 9;
  width: 100%;
}

/* square avatar */
.avatar {
  aspect-ratio: 1;
  width: 80px;
  border-radius: 50%;
}

/* golden ratio card */
.card {
  aspect-ratio: 1.618;
}

/* combined with object-fit for responsive images */
.thumb {
  aspect-ratio: 4 / 3;
  width: 100%;
  object-fit: cover;
}
14

カスタムプロパティ(変数)

変数の定義と使用

CSS カスタムプロパティ(変数)は --name で宣言し、var(--name) で使用します。:root で定義すればグローバルに、任意の要素にスコープすることもできます。プリプロセッサの変数と違いライブです:変数を変えるとすべての使用箇所がリアルタイムに更新され、カスケードと継承もします。var() は第 2 引数としてフォールバックを受け付け、変数が未定義のとき使われます。

css3
:root {
  --primary: #3490dc;
  --spacing: 16px;
  --max-width: 1200px;
}

.button {
  background: var(--primary);
  padding: var(--spacing);
  /* with fallback value (used if --primary undefined) */
  color: var(--text-color, #333);
}

/* override in a specific scope */
.dark-theme {
  --primary: #5a9fee;
}

テーマ化とダークモード

カスタムプロパティならテーマ化は簡単です:セマンティックな変数(--bg、--text、--primary)を定義し、[data-theme] セレクタで上書きします。<html> の data-theme 属性をトグルすれば、テーマ全体が瞬時に切り替わります — スタイルシートの複製は不要です。prefers-color-scheme と組み合わせれば、ユーザーの手動上書きを尊重する自動ダークモードになります。これがモダンで高性能なテーマ化の方法です。

css3
:root {
  --bg: #ffffff;
  --text: #1a1a1a;
  --primary: #3490dc;
}

[data-theme="dark"] {
  --bg: #1a1a1a;
  --text: #ffffff;
  --primary: #5a9fee;
}

body {
  background: var(--bg);
  color: var(--text);
}

/* auto dark mode via media query */
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg: #1a1a1a;
    --text: #ffffff;
  }
}

カスケードと継承

カスタムプロパティは通常の CSS のようにカスケードし継承します。.card で定義した変数は .card とすべての子孫で利用可能ですが、兄弟には利用できません。各要素は自分のスコープで変数の計算済みの値を読みます。@property(新しい機能)は構文、初期値、継承フラグを持つ型付きの変数を宣言でき — カスタムプロパティの滑らかな transition と animation が可能になります。

css3
:root { --color: blue; }       /* global */
.card { --color: green; }      /* scoped to .card */
.card .inner { color: var(--color); } /* green - inherits from .card */

/* variables inherit like other properties */
.parent { --size: 20px; }
.child { font-size: var(--size); } /* 20px via inheritance */

/* but: each element reads its own computed value */
.a { --x: 10px; }
.b { /* --x is NOT defined here, even if .a is sibling */ }

/* @property: typed variables with initial value */
@property --angle {
  syntax: "<angle>";
  inherits: false;
  initial-value: 0deg;
}

JavaScript との連携

CSS 変数は JavaScript から完全にアクセス可能です。getComputedStyle(el).getPropertyValue('--name') で読み(文字列が返り、先頭に空白があることが多い — trim しましょう)、el.style.setProperty('--name', value) で設定します。これでカスタムプロパティは強力な JS-CSS の橋になります:JS で変数を更新すれば CSS が即座に反応します — スクロール駆動の効果、テーマ化、動的レイアウトに最適です。

css3
/* read a variable */
const styles = getComputedStyle(document.documentElement);
const primary = styles.getPropertyValue("--primary"); /* "#3490dc" */

/* set a variable globally */
document.documentElement.style.setProperty("--primary", "#ff0000");

/* set on a specific element */
el.style.setProperty("--spacing", "24px");

/* inline style with variable */
<div style="--rotate: 45deg"></div>

/* useful pattern: expose JS values to CSS */
.root { --scroll: 0; }
.box { transform: rotate(calc(var(--scroll) * 1deg)); }

フォールバックとチェーン

var() は第 2 引数としてフォールバックをサポートします。これは変数が未定義のときだけ使われます(無効な値のときではない — 無効な値はプロパティ全体をデフォルトへフォールバックさせます)。フォールバックはチェーンできます:var(--a, var(--b, #default))。プログレッシブエンハンスメントやサードパーティコンポーネントの統合に有用です。@supports (--x: 0) でサポートを検出できますが、モダンブラウザすべてがカスタムプロパティに対応しています。

css3
.box {
  /* single fallback */
  color: var(--undefined, #333);
  
  /* chained: try --primary, fall back to --blue, then #00f */
  color: var(--primary, var(--blue, #0000ff));
  
  /* fallback in calc() */
  width: calc(100% - var(--sidebar, 250px));
  
  /* invalid values fall back to inherited/default */
  /* var() itself doesn't fail — the property does */
}

/* feature detection for custom property support */
@supports (--custom: property) {
  :root { --modern: true; }
}
15

Filter

Filter 関数

filter は要素に視覚効果を適用します。brightness/contrast/saturate は乗数(1 = 通常)かパーセンテージを取ります。hue-rotate はすべての色相を角度だけずらします。複数の filter は左から右へ連結されます。よくある用途:ホバー時のグレースケール画像、ビンテージ写真効果、背景の暗転。filter は要素、その背景、罫線、子に影響します。

css3
.blur { filter: blur(4px); }              /* gaussian blur in px */
.bright { filter: brightness(1.5); }     /* 1 = normal, >1 brighter */
.contrast { filter: contrast(200%); }    /* 100% = normal */
.gray { filter: grayscale(100%); }       /* 0-100% */
.sepia { filter: sepia(80%); }
.hue { filter: hue-rotate(90deg); }      /* rotate hue */
.invert { filter: invert(100%); }        /* invert colors */
.saturate { filter: saturate(2); }       /* 1 = normal */
.opacity { filter: opacity(50%); }

/* combine multiple filters (left-to-right) */
.vintage { filter: sepia(60%) contrast(110%) brightness(90%) saturate(1.2); }

drop-shadow

drop-shadow は box-shadow の filter 版です — ただしボックスではなく要素の実際の alpha 形状に従います。つまり影が PNG/SVG の切り抜きや不規則な形状に密着します。アイコンの影、光るロゴ、矩形以外の要素に使いましょう。複数の drop-shadow を重ねられます。注意:box-shadow より高コストになることがあるため、控えめに使いましょう。

css3
/* drop-shadow follows the alpha shape (unlike box-shadow) */
.cutout {
  filter: drop-shadow(4px 4px 8px rgba(0,0,0,0.4));
}

/* shadows on PNG with transparency - hugs the shape */
.logo {
  filter: drop-shadow(0 4px 6px rgba(0,0,0,0.3));
}

/* glow effect on text or SVG */
.icon {
  filter: drop-shadow(0 0 8px rgba(0, 150, 255, 0.8));
}

/* multiple drop-shadows layer */
.deep {
  filter: drop-shadow(0 1px 1px rgba(0,0,0,0.5))
          drop-shadow(0 2px 4px rgba(0,0,0,0.3));
}

backdrop-filter

backdrop-filter は要素の後ろにあるものすべてに filter を適用します — グラスモーフィズムの看板機能です。半透明の背景 + backdrop-filter: blur() ですりガラスの見た目になります。Safari のため必ず -webkit- 接頭辞を含めましょう。効果が現れるには要素の背景にいくらかの透明度が必要です。鮮やかな結果には saturate() と組み合わせ、縁の反射を模倣するため控えめな罫線を加えましょう。

css3
/* frosted glass effect */
.glass {
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px); /* Safari */
  border: 1px solid rgba(255, 255, 255, 0.3);
}

/* saturate + blur for vivid glass */
.vivid-glass {
  backdrop-filter: blur(16px) saturate(180%);
}

/* dark glass for dark mode */
.dark-glass {
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(12px);
}

Filter の組み合わせ

複数の filter は左から右へ適用されるため、順序が結果に影響します(例:hue-rotate の前に grayscale すると、回す色相がなくなります)。filter はアニメーション可能で GPU で高速化されます — ホバー効果に最適です。filter を mix-blend-mode と組み合わせると、要素を背景と混ぜ合わせられます。動的な制御には、filter チェーンをカスタムプロパティに保存し JS で更新しましょう。

css3
/* order matters: each filter feeds the next */
.artsy {
  filter: grayscale(100%) contrast(150%) brightness(110%);
}

/* animate filters smoothly */
img { transition: filter 0.3s; }
img:hover { filter: grayscale(0%) saturate(1.4); }

/* use CSS variables for dynamic filters */
.dynamic { filter: var(--photo-filter, none); }

/* layer with other effects */
.complex {
  filter: blur(1px) brightness(1.1);
  mix-blend-mode: multiply;
  opacity: 0.9;
}

Filter のパフォーマンス

filter は GPU で高速化されますが無料ではありません。フルスクリーン要素への大きな blur は重い再描画とカクつきを生みます(特にモバイル)。blur 半径は小さく保ち、filter 対象の領域を制限し、アニメーション発火の前に will-change: filter を適用しましょう。backdrop-filter は特に高コストです — フルセクションではなく小さな UI 要素に使いましょう。contain: paint で再描画領域を隔離するとパフォーマンスが向上します。

css3
/* AVOID: large blur on full-screen elements */
.janky { filter: blur(20px); } /* causes repaints */

/* BETTER: pre-blurred image, or limit blur area */
.smooth {
  filter: blur(2px); /* small radius is cheaper */
}

/* backdrop-filter is expensive - use sparingly */
/* contain: paint can limit repaint area */
.contained {
  contain: paint;
  backdrop-filter: blur(10px);
}

/* will-change prepares the GPU layer */
.prepared {
  will-change: filter;
  filter: blur(4px);
}
16

疑似要素

::before と ::after

::before と ::after は要素の実際のコンテンツの前後に生成コンテンツを挿入します。content プロパティが必須です(装飾要素なら空文字列でも)。コンテンツはテキスト、エスケープした Unicode、attr() 経由の属性値にできます。これらの疑似要素のデフォルトは inline です — ボックス状の装飾には display: block を設定しましょう。アイコン、装飾線、引用、フロートの解消に最適です。

css3
.quote::before { content: "\201C"; }  /* opening quote */
.quote::after  { content: "\201D"; }  /* closing quote */

/* icon via Unicode */
.warning::before { content: "\26A0"; margin-right: 6px; }

/* decorative element with content: "" */
.card::after {
  content: "";
  display: block;
  width: 50px; height: 2px;
  background: currentColor;
  margin-top: 12px;
}

/* content can use attributes */
a[href^="http"]::after {
  content: " (" attr(href) ")";
  font-size: 0.8em;
}

::first-letter と ::first-line

::first-letter は最初の文字を整形します — 記事のドロップキャップ(頭文字の装飾)に最適です。::first-line は最初の整形行を整形し、ビューポートの幅が変わると動的に調整されます。どちらもブロックレベル要素でしか機能しません。注意:::first-letter は最初の文字の前に他のコンテンツ(画像など)がないときだけ適用されます。編集レイアウトのタイポグラフィの必需品です。

css3
article p::first-letter {
  font-size: 3em;
  font-weight: bold;
  float: left;
  line-height: 0.8;
  margin-right: 8px;
  /* drop cap effect */
}

article p::first-line {
  text-transform: uppercase;
  letter-spacing: 1px;
  font-weight: bold;
}

/* only works on block-level elements */
/* affects the first formatted line (reflows with width) */

::selection

::selection はユーザーがハイライトしたテキスト部分を整形します。適用されるのはわずかなプロパティだけです:color、background-color、text-shadow、text-decoration。サイトに合わせた選択色のブランディングに使いましょう。::selection でグローバルに適用するか、特定の要素にスコープします。古い Firefox は ::-moz-selection を必要としましたが、モダンな Firefox は標準の ::selection に対応しています。

css3
/* style highlighted/selected text */
::selection {
  background: #b3d4fc;
  color: black;
  text-shadow: none;
}

/* scoped to specific elements */
p::selection { background: yellow; }
.highlight::selection { background: gold; color: #333; }

/* note: only a few properties work:
   color, background-color, text-shadow, 
   text-decoration (and its longhands) */

/* firefox historically used ::-moz-selection */

::placeholder と ::marker

::placeholder はフォーム入力のプレースホルダーテキストを整形します — Firefox のデフォルトは半透明なので opacity: 1 を設定しましょう。::marker はリスト項目の黒点や番号を整形し、限られたプロパティセット(color、content、font、direction)をサポートします。黒点はカスタムコンテンツ(Unicode、カウンタ)に置き換えられます。これらの疑似要素により、フォームとリストのスタイリングがデザイナーの完全な制御下に入ります。

css3
/* style input placeholder text */
input::placeholder {
  color: #999;
  font-style: italic;
  opacity: 1; /* Firefox applies opacity < 1 by default */
}

/* style list item markers (bullets/numbers) */
ul li::marker {
  color: red;
  font-size: 1.2em;
  content: "\25CF"; /* custom bullet */
}

ol li::marker {
  content: counter(list-item) ". ";
  color: blue;
  font-weight: bold;
}

/* ::marker supports: color, content, font properties,
   direction, unicode-bidi, text-transform, white-space */

生成コンテンツとカウンタ

::before/::after 経由の生成コンテンツには、counter() の値、属性値(attr())、文字列リテラルを含められます — 追加の DOM なしで CSS だけの番号付け、アイコン、ツールチップが実現します。counters() は「1.2.3」のようなネストした番号を作ります。attr(data-tooltip) とホバートランジションで作るツールチップは、JS ライブラリの軽量な代替です。注意:生成コンテンツは DOM に存在せず、読み上げないスクリーンリーダーもあります — 重要なコンテンツは置かないでください。

css3
/* counter in generated content */
h2::before {
  content: "Section " counter(section) ": ";
  color: gray;
}

/* attr() reads HTML attributes */
a::after {
  content: attr(data-icon);
}

/* counters() for nested numbering */
ol { counter-reset: item; }
li { display: block; }
li::before {
  content: counters(item, ".") " ";
  counter-increment: item;
}

/* CSS-only tooltip */
.tooltip::after {
  content: attr(data-tooltip);
  position: absolute;
  background: black; color: white;
  padding: 4px 8px;
  opacity: 0; transition: opacity 0.2s;
}
.tooltip:hover::after { opacity: 1; }
17

カウンタ

counter-reset と counter-increment

CSS カウンタで JavaScript なしに要素へ番号を付けられます。counter-reset がカウンタを初期化し(デフォルト 0、別の値から開始も可能)、counter-increment が増加させます(デフォルト 1、任意の整数が可能 — 負も)。値は content 内の counter() で表示します。カウンタはリセットした要素とその子孫にスコープされるため、ネストした番号付けが可能です。

css3
body { counter-reset: section; }   /* initialize to 0 */

h2 {
  counter-increment: section;  /* +1 each h2 */
}

h2::before {
  content: "Section " counter(section) ": ";
}

/* custom increment value */
ol { counter-reset: item; }
li { counter-increment: item 1; }  /* +1 (default) */
li.big { counter-increment: item 2; } /* +2 */

/* reset to a custom starting value */
.start-5 { counter-reset: item 4; } /* next increment = 5 */

counter() 関数

counter(name) はカウンタの現在値を出力し、counter(name, style) はリストスタイルを適用します:decimal(デフォルト)、lower/upper-alpha、lower/upper-roman、disc、square など。複数のカウンタを並行して動かし、content で組み合わせられます — 章ごとに番号を振る図(図 3-2)に最適です。カウンタの値は描画時に計算されるため、DOM が変わると自動的に更新されます。

css3
body { counter-reset: section; }
h2 { counter-increment: section; }
h2::before {
  content: "Chapter " counter(section) ". ";
  color: navy;
}

/* counter style (decimal, lower-alpha, upper-roman, etc.) */
h2::before {
  content: counter(section, upper-roman) ". ";
}

/* multiple counters */
body { counter-reset: section figure; }
h2 { counter-increment: section; }
figcaption { counter-increment: figure; }
figcaption::before {
  content: "Figure " counter(section) "-" counter(figure) ": ";
}

counters() によるネストしたカウンタ

counters(name, separator) はネストカウンタ用の関数です:すべての祖先スコープでのカウンタの値を、指定された文字列で区切って連結します。これにより「1.2.3」のようなアウトラインが自動的に作られます — 同じカウンタ名がネストした <ol> ごとにリセットされる仕組みです。counters()(複数形)がなければ、ネストしたリストはすべて同じ番号を共有してしまいます。区切り文字は '.' や '-' など任意の文字列です。

css3
ol { counter-reset: item; list-style: none; }
li::before {
  counter-increment: item;
  /* counters() concatenates ancestor counters with separator */
  content: counters(item, ".") " ";
}

/* produces: 1 / 1.1 / 1.2 / 2 / 2.1 / 2.1.1 ... */
<ol>
  <li>Item
    <ol>
      <li>Sub-item</li>
      <li>Sub-item</li>
    </ol>
  </li>
  <li>Item</li>
</ol>

/* custom separator */
li::before { content: counters(item, "-") ": "; }

カウンタのスタイリング

カウンタは多くの組み込みスタイルをサポートします:decimal、upper-roman、lower-alpha、lower-greek、cjk-decimal など。@counter-style でシンボルセット、システム(cyclic、additive、extends)、pad(先頭のゼロ埋め)、prefix/suffix、range などのオプションを持つカスタムスタイルを定義できます。テーマ化したリスト、絵文字の黒点、JavaScript なしのローカライズされた番号付けに最適です。

css3
/* built-in styles */
.decimal { content: counter(c, decimal); }
.roman { content: counter(c, upper-roman); }       /* I, II, III */
.alpha { content: counter(c, lower-alpha); }        /* a, b, c */
.greek { content: counter(c, lower-greek); }        /* alpha, beta, gamma */
.cjk { content: counter(c, cjk-decimal); }          /* CJK numerals */

/* @counter-style: define a custom style */
@counter-style thumbs {
  system: cyclic;
  symbols: "\1F44D"; /* thumbs up emoji */
  suffix: " ";
}
.like-list { list-style-type: thumbs; }

/* leading zeros via pad */
@counter-style padded {
  system: extends decimal;
  pad: 3 "0"; /* 001, 002, ... */
}

実用的なカウンタパターン

カウンタは番号付きのステップインジケーター、目次、アウトラインで輝きます。::before を円形のバッジ、色、数字で整形すれば、手動の番号付けなしで番号付きステップリストを作れます。DOM を編集すれば番号は自動更新されます。注意点:カウンタの値は JavaScript から簡単には読めません — 表示専用です。カウントに基づくロジックには、JS か CSS の :nth-child を使いましょう。

css3
/* numbered steps */
.steps { counter-reset: step; }
.steps li { counter-increment: step; }
.steps li::before {
  content: counter(step);
  display: inline-block;
  width: 28px; height: 28px;
  border-radius: 50%;
  background: var(--primary);
  color: white;
  text-align: center;
  line-height: 28px;
  margin-right: 10px;
}

/* "you've completed N sections" via counters (limited - 
   counters can't be read by JS easily, use them for display) */
18

マルチカラムレイアウト

column-count と column-width

マルチカラムレイアウトはコンテンツを新聞のような列に流し込みます。column-count は列数を固定し、column-width はブラウザに 250px の列が収まるだけ作らせます(メディアクエリなしのレスポンシブ)。省略形 columns は count か width(または両方)を取ります。マルチカラムは長文の読み物テキストに最適ですが、注意:短いコンテンツでは列の高さが不均一になることがあります。

css3
.article {
  /* fixed number of columns */
  column-count: 3;
  
  /* OR width-based (browser decides count) */
  column-width: 250px;
  
  /* shorthand (count width) */
  columns: 3 250px;
  columns: 3;       /* 3 columns */
  columns: 250px;   /* 250px columns, auto count */
}

/* responsive: width lets columns collapse on small screens */
.fluid { column-width: 200px; } /* 1 column on mobile, more on desktop */

column-gap と column-rule

column-gap は列間のスペースを設定します(現在は flexbox と grid も同じプロパティを使います)。column-rule は隙間に縦の区切り線を描きます — border の列版で、同じ省略形を使います。rule は余分な幅を取らず、隙間の中央に置かれます。控えめな色で列を区切り、押し付けがましくならないようにしましょう。

css3
.article {
  column-count: 3;
  column-gap: 30px;          /* space between columns */
  
  /* divider line (like border) */
  column-rule: 1px solid #ddd; /* shorthand */
  column-rule-width: 1px;
  column-rule-style: solid;
  column-rule-color: #ddd;
}

/* rule sits in the gap, doesn't add width */

column-span

column-span: all で要素が全列にまたがって割り込みます — マガジン風の見出しが全幅を取り、列はその上下に流れます。column-span: none(デフォルト)ではコンテンツは列を通して流れ続けます。大きな再フローを引き起こす可能性があり、サポートも不揃いだった歴史があるため、十分にテストしましょう。列ブロック間の見出しで最も確実に機能します。

css3
.article {
  column-count: 3;
}

/* heading spans all columns (like a magazine) */
.article h2 {
  column-span: all;
  /* resets above the heading, columns resume below */
}

/* default: content flows through columns */
.normal { column-span: none; }

/* note: column-span: all can cause reflow and is 
   not supported in older Firefox */

break-inside と列の区切り

マルチカラムのコンテンツは要素を列をまたいで不恰好に分割することがあります。break-inside: avoid で要素(カードや図など)を 1 列内で完全に保てます。break-before/break-after: column で列の区切りを強制します。古い page-break-* プロパティは別名として機能します。display: inline-block と width: 100% の組み合わせというハックが使われてきましたが、break-inside: avoid がモダンで正しいアプローチです。

css3
/* prevent an element from splitting across columns */
.card {
  break-inside: avoid;        /* modern */
  -webkit-column-break-inside: avoid; /* old webkit */
  page-break-inside: avoid;   /* old */
  display: inline-block;      /* hack for older browsers */
  width: 100%;
}

/* control where columns break */
h2 { break-after: column; }   /* force new column after */
h3 { break-before: column; }  /* force new column before */
p  { break-inside: avoid; }   /* keep paragraph together */

column-fill と均等化

column-fill はコンテンツを列へどう分配するかを制御します。balance(デフォルト)は高さを均等化し、列の終わりがほぼ揃います — 視覚的に整っています。auto は最初の列を満たしてから次へ進み、固定の高さが必要です — 印刷の挙動と一致します。一般的な用途には均等化された列がきれいです。コンテンツを厳密に上から下へ流したいときは auto が適しています。

css3
.article {
  column-count: 3;
  
  /* balance: equalize column heights (default in most browsers) */
  column-fill: balance;
  
  /* auto: fill first column fully, then next (needs height) */
  column-fill: auto;
  height: 500px; /* required for auto */
}

/* balanced columns look neat but can split awkwardly;
   auto is more like print, fills top-to-bottom */
19

ユーザーインターフェース

Outline とアクセシビリティ

目に見えるフォーカスインジケーターはアクセシビリティの要件です。:focus-visible はキーボードユーザー(マウスではない)にだけ輪郭を表示します — フォーカススタイリングのベストプラクティスです。代替(box-shadow のリングなど)なしに outline: none を設定してはいけません。outline-offset が要素と輪郭の間に余裕を加えます。モダンブラウザでは border-radius が輪郭の形状に影響するため、丸い輪郭がサポートされています。

css3
/* visible focus ring for keyboard users */
button:focus-visible {
  outline: 2px solid #0066cc;
  outline-offset: 2px;
}

/* never outline: none without a replacement */
/* custom focus ring via box-shadow */
button:focus {
  outline: none;
  box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.5);
}

/* outline shorthand */
.outlined { outline: 2px dashed red; outline-offset: 4px; }

/* thick rounded outline (modern browsers) */
button:focus-visible {
  outline: 3px solid blue;
  outline-offset: 2px;
  border-radius: 4px;
}

resize

resize はユーザーが要素をドラッグでリサイズできるかを制御します。textarea はデフォルトでリサイズ可能で、resize: none で無効化できます。vertical/horizontal/both が方向を制限します。resize が機能するには要素の overflow が visible 以外である必要があります(overflow: auto か hidden を設定)。テキストエリア、コードエディタ、ユーザーが調整できるパネルに有用です。

css3
textarea {
  /* allow vertical resize only (default for textarea) */
  resize: vertical;
  
  /* allow both axes */
  resize: both;
  
  /* horizontal only */
  resize: horizontal;
  
  /* disable resizing */
  .locked { resize: none; }
  
  /* default: inline/block elements can't be resized;
     textarea default is both in most browsers */
}

/* note: resize only works on overflow != visible */

caret-color と user-select

caret-color は編集可能な要素内の点滅するカーソルの色を設定します — ブランド化したフォームへの小さくて素敵な工夫です。user-select はテキストが選択できるかを制御します:none で無効化(UI コントロール用)、all でクリック時に要素全体を選択(コードブロックやメールに良い)、contain で選択を要素内に留めます。body への user-select: none は避けましょう — アクセシビリティを損ないます。

css3
/* color of the text cursor in inputs */
input, textarea {
  caret-color: #0066cc;  /* default: current color */
}

/* custom thick caret (limited support) */
input { caret-color: red; }

/* control text selection by the user */
.no-select { user-select: none; }        /* disable selection */
.select-all { user-select: all; }        /* select whole element on click */
.select-text { user-select: text; }      /* normal text selection */
.select-contain { user-select: contain; } /* selection stays within */

/* email addresses, code blocks often user-select: all */

appearance とフォームのスタイリング

appearance: none はフォームコントロールからネイティブの OS スタイルを剥ぎ取り、CSS で完全に整形できるようにします — ブラウザ間で一貫したフォームデザインには不可欠です。ネイティブのセレクトの矢印を取り除いたら、カスタムの background-image を加えましょう。カスタムのチェックボックスは appearance: none と状態のための :checked を使います。完全なサポートのため必ず -webkit-/-moz- 接頭辞を付け、ブラウザ間で十分にテストしてください — 一部のコントロール(date、color)は完全な再スタイルが依然難しいです。

css3
/* remove native widget styling */
input, select, button {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

/* custom select arrow (after removing native) */
select {
  background-image: url("arrow.svg");
  background-repeat: no-repeat;
  background-position: right 10px center;
  padding-right: 30px;
}

/* style checkbox/radio with appearance: none */
input[type="checkbox"] {
  appearance: none;
  width: 20px; height: 20px;
  border: 2px solid #999;
  border-radius: 4px;
}
input[type="checkbox"]:checked {
  background: var(--primary);
  border-color: var(--primary);
}

scroll-behavior とスクロールバー

<html> への scroll-behavior: smooth で、アンカーリンクのクリックがジャンプではなくターゲットへアニメーションします — 感受性の強いユーザーのために prefers-reduced-motion と組み合わせて無効化しましょう。カスタムスクロールバー:標準の scrollbar-width/scrollbar-color プロパティは Firefox とモダン Chrome で動き、::-webkit-scrollbar 疑似要素は WebKit/Blink でより細かい制御を提供します。控えめなカスタムスクロールバーがスクロール領域の UX を磨きます。

css3
/* smooth scrolling for anchor links */
html { scroll-behavior: smooth; }

/* respect reduced motion */
@media (prefers-reduced-motion: reduce) {
  html { scroll-behavior: auto; }
}

/* custom scrollbar (WebKit) */
.scroll-area::-webkit-scrollbar { width: 8px; }
.scroll-area::-webkit-scrollbar-track { background: #f1f1f1; }
.scroll-area::-webkit-scrollbar-thumb { background: #888; border-radius: 4px; }
.scroll-area::-webkit-scrollbar-thumb:hover { background: #555; }

/* standard scrollbar-color (Firefox + spec) */
.scroll-area {
  scrollbar-width: thin;
  scrollbar-color: #888 #f1f1f1;
}
20

高度でモダンな機能

Scroll Snap

Scroll Snap は JavaScript なしでカルーセル風や全ページスクロールを作れます。scroll-snap-type: x/y + mandatory/proximity が軸と厳格さを制御します。scroll-snap-align を持つ子が start/center/end へスナップします。mandatory はスナップを強制し(全ページのセクションに良し)、proximity は近いときだけスナップします(穏やかで、画像ギャラリー向け)。スティッキーヘッダーの下のスナップポイントのオフセットには scroll-margin と組み合わせましょう。

css3
.gallery {
  scroll-snap-type: x mandatory;  /* snap horizontally, must snap */
  overflow-x: auto;
  display: flex;
}

.gallery > img {
  scroll-snap-align: center;   /* start | center | end */
  scroll-snap-stop: always;    /* can't skip snaps */
  flex: 0 0 80%;
}

/* vertical full-page snap */
.pages {
  scroll-snap-type: y mandatory;
  height: 100vh;
  overflow-y: scroll;
}
.page { scroll-snap-align: start; height: 100vh; }

/* proximity: only snaps when close (gentler) */
.soft { scroll-snap-type: y proximity; }

object-fit と object-position

object-fit は <img> や <video> がボックスをどう満たすかを制御します — メディア版の background-size です。cover はボックスを満たして溢れを切り落とし、contain は空きスペースが生じうる形でメディア全体を収め、fill は引き伸ばします(歪む)。object-position が焦点を設定します — cover が画像の重要な部分を切り落とすときに有用です。これでレスポンシブメディアのための background-image ハックが不要になります。

css3
/* cover: fill box, crop overflow (like background-size: cover) */
.avatar img {
  width: 100px; height: 100px;
  object-fit: cover;        /* cover | contain | fill | none | scale-down */
  object-position: center;  /* position the focal point */
  border-radius: 50%;
}

/* contain: whole image visible, may letterbox */
.preview img {
  width: 300px; height: 200px;
  object-fit: contain;
  background: #eee;
}

/* object-position shifts the visible area */
.banner img {
  width: 100%; height: 300px;
  object-fit: cover;
  object-position: top;  /* show top of image */
}

will-change

will-change はブラウザに「このプロパティがまもなく変わる」と知らせ、GPU レイヤーの事前確保と最適化を可能にします。アニメーションの直前に適用し、後に取り除きましょう — 多くの要素での恒常的な使用はメモリを浪費しパフォーマンスを損ないます。実際にアニメーションするプロパティだけ(transform、opacity、filter)を列挙します。乱用は意図した効果の逆を招くため、控えめに意図的に使ってください。

css3
/* hint that an element will animate transform */
.card { will-change: transform; }

/* remove when not needed (frees GPU memory) */
.card.idle { will-change: auto; }

/* multiple properties */
.complex { will-change: transform, opacity; }

/* AVOID: permanent will-change on many elements */
/* .all { will-change: transform, opacity, top, left; } */ /* bad */

/* apply just before animation, remove after */
.prepare { will-change: transform; }
/* JS: el.classList.add('prepare'); 
   setTimeout(() => el.classList.remove('prepare'), 1000); */

contain

contain はブラウザに「この要素はページの他の部分と独立している」と伝え、大きなパフォーマンス最適化を可能にします — contain された要素の内側の変更は外側の再計算をトリガーしません。layout、paint、style、size が隔離の種類です。strict(すべて、size を含む)が最も強力です。再フロー/再描画のコストを制限するため、繰り返し表示されるウィジェット、リスト項目、広告に適用しましょう。size には明示的な寸法が必要です。

css3
/* isolate an element's layout/paint/style from the rest */
.widget {
  contain: layout paint style;  /* or: strict, content */
  
  /* size: the element's size is independent of its children */
  contain: size;  /* needs explicit dimensions */
}

/* layout: changes inside don't affect outside layout */
/* paint: children don't render outside the box (clipped) */
/* style: counters and quotes are scoped */
/* size: element ignores children for sizing */

/* full isolation */
.isolated { contain: strict; } /* = size layout paint style */
.content-isolated { contain: content; } /* = layout paint style */

/* useful for performance on complex widgets, lists, ads */

aspect-ratio と普遍化した gap

aspect-ratio は任意の要素で幅:高さの比を保ち、メディアの読み込み中のレイアウトシフトを防ぎます。gap(とその個別指定 row-gap/column-gap)はモダンなスペーシングの道具で、flexbox、grid、マルチカラムで機能します — .item + margin + :last-child のハックを不要にします。どちらもモダンブラウザで普遍的にサポートされ、合わせて CSS の最も一般的な 2 つの悩み(メディアの比の維持とアイテム間隔のきれいな処理)を解決します。

css3
/* aspect-ratio works on any element */
.video-wrap {
  aspect-ratio: 16 / 9;
  background: black;
}

/* gap works in flex, grid, and multi-column */
.flex { display: flex; gap: 16px; }
.grid { display: grid; gap: 16px; }
.cols { column-count: 3; column-gap: 16px; }

/* row-gap / column-gap longhands */
.layout {
  display: grid;
  row-gap: 24px;
  column-gap: 16px;
}

/* gap replaced margin-based spacing hacks */
/* (no more .item:last-child { margin-right: 0 }) */

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.