セレクタ
基本セレクタ
CSS セレクタはスタイリングのために HTML 要素をターゲットにします。タイプセレクタは要素名(p、div)にマッチします。クラスセレクタ(.)は class 属性にマッチし再利用可能です。ID セレクタ(#)は単一要素にマッチし一意であるべきです。ユニバーサルセレクタ(*)はすべてにマッチします。カンマでグループ化してスタイルを共有します。
/* Type selector - all <p> elements */
p { color: #333; }
/* Class selector - elements with class="btn" */
.btn { padding: 8px 16px; }
/* ID selector - element with id="header" */
#header { background: #fff; }
/* Universal selector - all elements */
* { box-sizing: border-box; }
/* Grouping selector */
h1, h2, h3 { font-family: Arial, sans-serif; }コンビネータ
コンビネータは要素間の関係を定義します。子孫(スペース)はネストされた任意の要素にマッチします。子(>)は直接の子のみにマッチします。隣接兄弟(+)は直後の要素にマッチします。一般兄弟(~)は後のすべての兄弟にマッチします。コンビネータの理解は余分なクラスなしの精密なスタイリングに不可欠です。
/* Descendant - any <a> inside .nav */
.nav a { text-decoration: none; }
/* Child - direct <li> children of <ul> */
ul > li { list-style: none; }
/* Adjacent sibling - <p> right after <h1> */
h1 + p { font-size: 1.2em; }
/* General sibling - all <p> after <h1> */
h1 ~ p { color: gray; }属性セレクタ
属性セレクタは属性値に基づいて要素にマッチします。[attr] は存在にマッチします。[attr=val] は完全一致にマッチします。^= は接頭辞、$= は接尾辞、*= は部分文字列にマッチします。これらはフォーム入力、タイプ別リンク、data 属性を持つ要素を余分なクラスなしでスタイリングするのに強力です。
/* Elements with type attribute */
[type] { border: 1px solid #ccc; }
/* Exact match */
[type="text"] { padding: 4px; }
/* Starts with */
a[href^="https"] { color: green; }
/* Ends with */
a[href$=".pdf"] { color: red; }
/* Contains */
a[href*="example"] { font-weight: bold; }疑似クラス
疑似クラスは状態や位置に基づいて要素を選択します。インタラクティブ::hover、:focus、:active、:visited、:disabled。構造的::first-child、:last-child、:nth-child(n)、:nth-of-type(n)。:not() はセレクタを否定します。:nth-child(odd/even) はゼブラストライプを作成します。:nth-child(3n) は 3 番目ごとの要素を選択します。これらは余分なクラスの必要性を減らします。
/* Interactive states */
a:hover { color: red; }
a:visited { color: purple; }
input:focus { border-color: blue; }
input:disabled { background: #eee; }
button:active { transform: scale(0.98); }
/* Structural */
li:first-child { font-weight: bold; }
li:last-child { border: none; }
li:nth-child(odd) { background: #f9f9f9; }
li:nth-child(3n) { color: blue; }
p:not(.highlight) { color: #333; }疑似要素
疑似要素(::ダブルコロン)は要素の特定部分をスタイルします。::before と ::after は生成コンテンツを挿入します(content プロパティが必要)。::first-letter と ::first-line はテキスト部分をスタイルします。::selection はハイライトされたテキストをスタイルします。::placeholder は入力プレースホルダーをスタイルします。注意:::before/::after はデフォルトでインラインです — ブロック動作には display:block を設定してください。
/* First line of a paragraph */
p::first-line { font-weight: bold; }
/* First letter (drop cap) */
p::first-letter { font-size: 3em; float: left; }
/* Insert content before/after */
.quote::before { content: "\201C"; }
.quote::after { content: "\201D"; }
/* Selection styling */
::selection { background: yellow; color: black; }
/* Placeholder styling */
input::placeholder { color: #999; }詳細度と !important
詳細度はセレクタが競合する時にどのルールが適用されるかを決定します。インラインスタイル > ID > クラス > タイプ。詳細度が同点の場合、最後のルールが勝ちます。!important はすべてを上書きしますがカスケードを壊します — 避けてください。DevTools で詳細度を調査します。メンテナンス性のためクラスベースのセレクタを優先します。クラスの繰り返し(.btn.btn)で詳細度を上げるのはハックです — 避けてください。
/* Specificity hierarchy (low to high):
1. Type selectors (p, div) = 0,0,0,1
2. Class selectors (.btn) = 0,0,1,0
3. ID selectors (#header) = 0,1,0,0
4. Inline styles (style="...") = 1,0,0,0
5. !important = overrides all
*/
/* ID beats class */
#nav .link { color: red; } /* wins */
.nav .link { color: blue; }
/* Avoid !important unless necessary */
.critical { color: red !important; }ボックスモデル
Margin と Padding
すべての要素はコンテンツ、パディング、ボーダー、マージンを持つボックスです。パディングはボーダーの内側(背景に影響)、マージンは外側(透明)です。ショートハンド:1 値 = 全辺、2 値 = 上下 左右、3 = 上 左右 下、4 = 上 右 下 左(時計回り)。margin: 0 auto は定義された幅を持つブロック要素を中央揃えします。
.box {
/* TRBL: top right bottom left */
margin: 10px 20px 10px 20px;
/* Shorthand: top/bottom left/right */
margin: 10px 20px;
/* All sides */
padding: 15px;
/* Individual sides */
margin-top: 0;
padding-left: 24px;
/* Center horizontally (block) */
margin: 0 auto;
}Border と Outline
border はパディングの周りに線を追加しレイアウトに影響します。outline はレイアウトに影響せずボーダー の外側に描画します — フォーカスインジケータに便利です。border-radius は角を丸めます(単一値またはコーナーごと:左上 右上 右下 左下)。outline-offset はボーダーとアウトライン間にスペースを追加します。アクセシビリティのために常に可視のフォーカススタイルを提供してください。
.box {
/* Shorthand: width style color */
border: 2px solid #333;
/* Individual sides */
border-bottom: 3px dashed red;
border-radius: 8px;
/* Outline (doesn't affect layout) */
outline: 2px solid blue;
outline-offset: 4px;
}
/* Remove default focus, add custom */
button:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(0,123,255,0.5);
}Box Sizing
box-sizing: content-box(デフォルト)は width/height がコンテンツのみに適用されることを意味します — パディングとボーダーが合計サイズに追加されます。box-sizing: border-box はパディングとボーダーを width/height に含め、サイジングを予測可能にします。一貫したレイアウトのために常にグローバルに border-box を設定してください。これは最も重要な CSS リセットの一つです。
/* Default: width = content only */
.content-box {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 5px solid;
/* Total width: 200 + 40 + 10 = 250px */
}
/* Recommended: width includes padding+border */
.border-box {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid;
/* Total width: 200px */
}
/* Apply globally */
*, *::before, *::after {
box-sizing: border-box;
}Box Shadow
box-shadow はシャドウ効果を追加します:offset-x offset-y blur-radius spread-radius color。正のオフセットはシャドウを右/下に移動します。inset は内側のシャドウを作成します。複数のシャドウはレイヤー化されます(最初 = 最前面)。自然にブレンドする半透明シャドウには rgba を使用します。シャドウは奥行きに最適ですが過度の使用はパフォーマンスを損ないます — 控えめなシャドウを優先してください。
/* offset-x offset-y blur spread color */
.card {
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
/* Multiple shadows */
.button {
box-shadow:
0 1px 2px rgba(0,0,0,0.1),
0 4px 8px rgba(0,0,0,0.05);
}
/* Inset shadow */
.input:focus {
box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
}
/* No shadow */
.no-shadow { box-shadow: none; }Display と Visibility
display: none は要素をレイアウトから完全に削除します(スペースなし)。visibility: hidden は非表示にしますがスペースを保持します。opacity: 0 は透明にしますがインタラクティブのままです。block 要素は全幅を取り改行します。inline 要素はテキストに流れます。inline-block はインラインフローとブロック寸法(width、height)を組み合わせます。コンテンツのトグルには display: none を使用します。
/* Display types */
div { display: block; } /* full width, line break */
span { display: inline; } /* content width, no break */
.inline-block { display: inline-block; } /* inline but block props */
.flex { display: flex; } /* flex container */
.grid { display: grid; } /* grid container */
.none { display: none; } /* removed from layout */
/* Visibility (keeps space) */
.hidden { visibility: hidden; }
/* Opacity (keeps space, can interact) */
.fade { opacity: 0; }色と単位
カラーフォーマット
CSS は複数のカラーフォーマットをサポートします。Hex(#rrggbb)が最も一般的です。RGB/RGBA はアルファ透明度を追加します。HSL(色相 0-360、彩度%、輝度%)は直感的です — 色相を変えて色をシフトし、輝度でシェードを作ります。currentColor は要素の color プロパティを継承します。現代の CSS はより広い色域の oklch() と color() もサポートします。透明度には rgba/hsla を使用します。
/* Named colors */
.color { color: red; background: tomato; }
/* Hexadecimal */
.hex { color: #ff6600; } /* 6-digit */
.hex-short { color: #f60; } /* 3-digit shorthand */
/* RGB / RGBA */
.rgb { color: rgb(255, 102, 0); }
.rgba { background: rgba(0, 0, 0, 0.5); }
/* HSL / HSLA (hue, saturation, lightness) */
.hsl { color: hsl(20, 100%, 50%); }
.hsla { background: hsla(120, 100%, 50%, 0.3); }
/* Current color keyword */
.box { color: blue; border: 2px solid currentColor; }長さの単位
px は絶対的で予測可能です。em は親の font-size に相対します(ネスト時に累積)。rem はルート(html)の font-size に相対です — 一貫性 がありアクセシビリティに推奨されます。% は親に相対します。vh/vw はビューポートに相対です(100vh = フル高さ)。フォントサイズには rem、レイアウトには %、ボーダー/細かい詳細には px を使用します。
/* Absolute units */
.px { font-size: 16px; } /* 1px = 1/96 inch */
.pt { font-size: 12pt; } /* 1pt = 1/72 inch */
/* Relative to parent font-size */
.em { font-size: 1.5em; } /* 1.5x parent */
/* Relative to root font-size (html) */
.rem { font-size: 1.2rem; } /* 1.2x root (usually 16px) */
/* Relative to parent dimensions */
.pct { width: 50%; } /* 50% of parent */
/* Viewport units */
.vh { height: 100vh; } /* 100% of viewport height */
.vw { width: 50vw; } /* 50% of viewport width */
.vmin { font-size: 2vmin; } /* 2% of smaller dimension */CSS 関数
calc() は混合単位で計算します(例:100% - 250px)。min() は最小値を選びます(レスポンシブ max-width に最適)。max() は最大値を選びます。clamp(min, preferred, max) は範囲間でスケールする流体値を作成します — レスポンシブタイポグラフィに完璧です。var() はオプションのフォールバック付きでカスタムプロパティを参照します。これらの関数によりメディアクエリなしで CSS が動的になります。
/* calc() - mathematical calculations */
.sidebar { width: calc(100% - 250px); }
.gap { margin: calc(1rem + 10px); }
/* min() / max() - choose smaller/larger */
.responsive { width: min(90%, 1200px); }
.min-width { width: max(300px, 50%); }
/* clamp() - fluid sizing with bounds */
.title { font-size: clamp(1.5rem, 4vw, 3rem); }
/* var() - use custom properties */
.btn { color: var(--primary, #007bff); }グラデーション
グラデーションは滑らかな色の遷移を作成します。linear-gradient(direction, color1, color2) は方向に進みます(to right、45deg)。radial-gradient は中心点から広がります。conic-gradient は中心の周りを回転します。位置付きのカラーストップを追加できます:linear-gradient(to right, red 0%, blue 50%, green 100%)。グラデーションは色ではなく画像であり、background-image が受け入れられる場所ならどこでも使用できます。
/* Linear gradient */
.bg1 {
background: linear-gradient(to right, #ff0000, #0000ff);
}
/* Diagonal with angle */
.bg2 {
background: linear-gradient(45deg, #ff0000, #00ff00, #0000ff);
}
/* Radial gradient */
.bg3 {
background: radial-gradient(circle, #ff0000, #0000ff);
}
/* Conic gradient */
.bg4 {
background: conic-gradient(red, yellow, green, blue, red);
}フィルターとブレンドモード
filter は視覚効果を適用します:blur()、brightness()、contrast()、grayscale()、sepia()、hue-rotate()、invert()、opacity()、saturate()。複数のフィルターが連鎖します。mix-blend-mode は要素を背後のものとブレンドします(multiply、screen、overlay など)。backdrop-filter は要素の背後の領域にフィルターを適用します(グラスモーフィズムに最適)。フィルターはパフォーマンスに影響する可能性があります — 控えめに使用してください。
/* Filters */
img.bw { filter: grayscale(100%); }
img.blur { filter: blur(5px); }
img.bright { filter: brightness(1.5); }
img.sepia { filter: sepia(0.8); }
/* Multiple filters */
img.vintage {
filter: sepia(0.5) contrast(1.2) brightness(0.9);
}
/* Blend mode */
.overlay {
background: rgba(255,0,0,0.5);
mix-blend-mode: multiply;
}タイポグラフィ
フォントプロパティ
font-family はフォールバックリストを受け入れます — ブラウザが最初に利用可能なものを使用します。常に汎用ファミリー(serif、sans-serif、monospace)で終わらせてください。font-weight は 100(thin)から 900(black)の範囲です。line-height: 1.5 はフォントサイズの 1.5 倍を意味します — 1.4-1.6 が本文の可読性に理想的です。font ショートハンドには最低でも size と family を含める必要があります。
body {
/* Font shorthand: style weight size/line-height family */
font: italic bold 16px/1.5 Arial, sans-serif;
/* Individual properties */
font-family: "Helvetica Neue", Arial, sans-serif;
font-size: 16px;
font-weight: 400; /* 100-900, normal=400, bold=700 */
font-style: italic; /* normal, italic, oblique */
line-height: 1.5;
}テキストスタイリング
text-align は水平配置を制御します。text-decoration は線を追加します(underline、overline、line-through)。text-transform は大文字小文字を変更します。letter-spacing(トラッキング)と word-spacing は文字と 単語間の間隔を調整します。white-space: nowrap はテキストの折り返しを防ぎます。垂直配置には vertical-align(インライン)または flexbox/grid 配置(ブロック)を使用します。
p {
text-align: justify; /* left, right, center, justify */
text-decoration: underline; /* none, overline, line-through */
text-transform: capitalize; /* uppercase, lowercase, capitalize */
text-indent: 2em; /* indent first line */
letter-spacing: 0.05em; /* tracking */
word-spacing: 0.1em;
white-space: nowrap; /* prevent wrapping */
}
a {
text-decoration: none;
color: #0066cc;
}テキストオーバーフローと折り返し
省略記号でテキストを切り詰めるには 3 つのプロパティが必要です:white-space: nowrap、overflow: hidden、text-overflow: ellipsis。overflow-wrap: break-word は長い単語を分割してオーバーフローを防ぎます。word-break: break-all は任意の文字で分割します。text-wrap: balance(新しい)は見出しの行長をバランスさせます。切り詰めを機能させるには常に max-width または width を設定してください。
/* Truncate with ellipsis */
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
/* Break long words */
.break-word {
overflow-wrap: break-word;
word-break: break-all;
}
/* Balance text wrapping (newer) */
h1 {
text-wrap: balance;
}Web フォント(@font-face)
@font-face はカスタムフォントを読み込みます。woff2 がモダンフォーマット(最高圧縮)です。フォールバックとして woff を提供します。font-display: swap はフォールバックテキストを即座に表示し、フォント読み込み後に置き換えます(不可視テキストを防ぐ)。常にフォールバックフォントファミリーを宣言してください。Google Fonts は @import または <link> でホストフォントを提供します。パフォーマンスのために重要なフォントをプリロードします。
@font-face {
font-family: 'MyCustomFont';
src: url('fonts/custom.woff2') format('woff2'),
url('fonts/custom.woff') format('woff');
font-weight: 400;
font-style: normal;
font-display: swap;
}
body {
font-family: 'MyCustomFont', Arial, sans-serif;
}
/* Google Fonts import */
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');リストとリンクのスタイリング
list-style: none はカスタムナビゲーションやスタイル付きリストのデフォルト箇条書きを削除します。list-style-type は箇条書きを変更します(disc、circle、square、decimal、none)。list-style-position: inside は箇条書きをコンテンツエリア内に配置します。リンクには LVHA 順序が重要です::link、:visited、:hover、:active。これはリンク状態の適切なカスケードを保証します。
/* Reset list styles */
ul {
list-style: none;
padding: 0;
margin: 0;
}
/* Custom bullets */
ul.custom {
list-style-type: square;
list-style-position: inside;
}
/* Image bullets */
ul.image {
list-style-image: url('bullet.png');
}
/* Link states (order matters!) */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; text-decoration: underline; }
a:active { color: orange; }Flexbox レイアウト
Flex コンテナ
display: flex は flex コンテナを作成します。justify-content は主軸に沿ってアイテムを整列させます(row では水平)。align-items は交差軸に沿って整列させます(垂直)。flex-direction は主軸を変更します。flex-wrap はアイテムが新しい行に折り返すことを許可します。gap はアイテム間の間隔を設定します(マージンハックを置き換え)。Flexbox は 1D レイアウト(行または列)に理想的です。
.container {
display: flex;
/* Main axis alignment */
justify-content: space-between;
/* flex-start, center, flex-end, space-around, space-evenly */
/* Cross axis alignment */
align-items: center;
/* flex-start, center, flex-end, stretch, baseline */
/* Direction */
flex-direction: row;
/* row, row-reverse, column, column-reverse */
/* Wrapping */
flex-wrap: wrap;
/* nowrap, wrap, wrap-reverse */
/* Gap between items */
gap: 16px;
}Flex アイテム
flex-grow はアイテムが余分なスペースを共有する方法を制御します(0 = 成長しない、1 = 均等に成長)。flex-shrink はスペースが限られた時にアイテムが縮む方法を制御します。flex-basis は初期サイズを設定します。ショートハンド flex: 1 は flex-grow:1、flex-shrink:1、flex-basis:0% を意味します。align-self は 1 つのアイテムのコンテナの align-items を上書きします。order は DOM を変更せずに視覚的にアイテムを並べ替えます。
.item {
/* Grow: how much space to take (0 = don't grow) */
flex-grow: 1;
/* Shrink: how much to shrink when space is tight */
flex-shrink: 0;
/* Basis: initial size before growing/shrinking */
flex-basis: 200px;
/* Shorthand: flex: grow shrink basis */
flex: 1 0 200px;
/* Override align-items for this item */
align-self: flex-end;
/* Order (default 0, lower = earlier) */
order: -1;
}一般的な Flexbox パターン
Flexbox は中央揃えを簡単にします:justify-content: center + align-items: center。スティッキーフッターには、body を min-height: 100vh の flex カラムにし、メインコンテンツを flex: 1 にします。ナビバーには justify-content: space-between で最初と最後のアイテムを反対側に押します。これらのパターンは flexbox 以前は困難だった一般的なレイアウト問題を解決します。
/* Center anything */
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* Sticky footer */
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main { flex: 1; }
/* Navbar: logo left, links right */
.nav {
display: flex;
justify-content: space-between;
align-items: center;
}Flex Direction と Wrap
flex-direction: column は垂直レイアウトを作成します(スタッキングに便利)。flex-wrap: wrap はスペースがなくなった時にアイテムが新しい行に流れることを許可します。flex: 1 1 300px はアイテムが 300px で開始し、スペースを埋めるために成長し、必要に応じて縮むことを意味します。align-content は折り返された行間の間隔を制御します(wrap でのみ動作)。このパターンはレスポンシブカードグリッドを作成します。
/* Horizontal (default) */
.row { display: flex; flex-direction: row; }
/* Vertical */
.column { display: flex; flex-direction: column; }
/* Reverse */
.row-rev { display: flex; flex-direction: row-reverse; }
/* Wrap to new lines */
.cards {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card { flex: 1 1 300px; } /* grow, shrink, basis */
/* Align wrapped lines */
.cards { align-content: space-between; }Flexbox 配置の詳細
flex-direction: column では、主軸は垂直で交差軸は水平です — justify-content と align-items は役割を交換します。flex アイテムの margin: auto は利用可能なすべてのスペースを吸収し、完全に中央揃えします。これは justify-content/align-items の代替です。どの軸が「主」でどちらが「交差」かを理解することが flexbox 配置の習得の鍵です。
.container {
display: flex;
flex-direction: column;
/* Main axis = vertical (column) */
justify-content: flex-start;
/* push items to top, center, bottom, or spread */
/* Cross axis = horizontal (column) */
align-items: stretch;
/* stretch items to full width */
}
/* Center a single item perfectly */
.wrapper {
display: flex;
min-height: 100vh;
}
.centered {
margin: auto; /* centers in both axes */
}CSS Grid レイアウト
Grid コンテナ
display: grid は 2D レイアウトを作成します。grid-template-columns は列サイズを定義します:fr 単位は空きスペースを比例配分します。repeat(3, 1fr) は 3 つの等しい列を作成します。repeat(auto-fit, minmax(250px, 1fr)) は列数を自動調整するレスポンシブグリッドを作成します — これはレスポンシブグリッドの「聖杯」です。gap が間隔のためにマージンを置き換えます。
.grid {
display: grid;
/* Define columns */
grid-template-columns: 200px 1fr 200px;
/* fixed, flexible, fixed */
/* Or repeat */
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
/* Define rows */
grid-template-rows: auto 1fr auto;
/* Gap (formerly grid-gap) */
gap: 20px;
row-gap: 10px;
column-gap: 20px;
}Grid アイテムの配置
Grid アイテムは grid-column: span N で複数セルにまたがれます。行番号も使用できます:grid-column: 1 / 3 は行 1 から開始し行 3 で終了することを意味します。行は 1(左/上)から N+1(右/下)に番号付けされます。grid-area はアイテムを名前付きエリアに割り当てます。Grid は精密な 2D 配置を可能にします — アイテムは行と列を同時にまたがれます。
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
/* Span multiple columns */
.featured {
grid-column: span 2;
}
/* Explicit placement */
.sidebar {
grid-column: 1 / 3; /* start at line 1, end at line 3 */
grid-row: 1 / 4;
}
/* Named areas */
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }Grid Template Areas
grid-template-areas は名前付き文字列を使用してレイアウトの視覚的マップを作成します。各文字列は行を表し、各名前は列を表します。アイテムは grid-area を一致する名前に設定して配置されます。これは複雑なレイアウトを作成する最も読みやすい方法です。空のセルには '.' を使用します。同じ名前が複数セルにまたがれます。レスポンシブレイアウトのためにメディアクエリでエリアを変更します。
.layout {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
gap: 10px;
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }Grid 配置
Grid には 6 つの配置プロパティがあります。align-items/justify-items はグリッドセル内のアイテムを整列させます。align-content/justify-content はコンテナ内のグリッドトラック全体を整列させます(グリッドが小さい場合のみ可視)。align-self/justify-self はアイテムごとに上書きします。place-items: center は align-items + justify-items のショートハンドです。place-content: center は両方のコンテンツ配置を組み合わせます。
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
/* Align items within their cell (cross axis) */
align-items: center; /* start, center, end, stretch */
/* Justify items within their cell (main axis) */
justify-items: center;
/* Align the entire grid (if smaller than container) */
align-content: center;
justify-content: center;
}
/* Override for individual item */
.item {
align-self: end;
justify-self: start;
}レスポンシブ Grid(Auto-fit)
repeat(auto-fit, minmax(300px, 1fr)) は利用可能なスペースに基づいて列数を自動調整するグリッドを作成します — アイテムは少なくとも 300px で成長して埋めます。これはカードレイアウトのメディアクエリを排除します。auto-fill は空の列を保持し(アイテムは左に留まる)、auto-fit はそれらを折りたたみます(アイテムは伸びる)。ほとんどのケースで auto-fit を使用します。最適な結果のためにコンテナの max-width と組み合わせます。
/* Auto-responsive grid - no media queries needed! */
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
/* Fixed number of columns per breakpoint */
@media (min-width: 768px) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1024px) {
.cards {
grid-template-columns: repeat(3, 1fr);
}
}
/* Auto-fill vs auto-fit:
auto-fit collapses empty tracks
auto-fill keeps empty tracks */ポジショニング
Position タイプ
static はデフォルト(通常のドキュメントフロー)です。relative は通常位置からオフセットし他の要素に影響しません(配置コンテキストを作成)。absolute はフローから削除し最も近い配置された祖先に相対的に配置します。fixed はビューポートに相対的に配置します(スクロールで固定)。sticky は relative と fixed を切り替えます — 通常スクロールし、しきい値で固定されます。
/* Static (default) - normal flow */
.static { position: static; }
/* Relative - offset from 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 */
.fixed {
position: fixed;
bottom: 0;
width: 100%;
}
/* Sticky - scrolls then sticks */
.sticky {
position: sticky;
top: 0;
}Absolute ポジショニング
absolute ポジショニングには配置された祖先(relative、absolute、fixed、sticky)が必要です。ない場合、ビューポートに相対的に配置します。top/right/bottom/left プロパティは対応するエッジからオフセットします。絶対配置要素を中央揃えするには、top:50%、left:50% と transform: translate(-50%,-50%) を使用します。absolute ポジショニングは要素を通常フローから削除します。
/* Parent must be positioned */
.container {
position: relative;
width: 400px;
height: 300px;
}
/* Position relative to container */
.badge {
position: absolute;
top: 10px;
right: 10px;
}
/* Center absolutely positioned element */
.modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}Sticky ポジショニング
position: sticky はハイブリッドです — 要素はしきい値(例:top: 0)に達するまで通常スクロールし、その後固定されます。スティッキーヘッダー、サイドバー、テーブルヘッダーに最適です。要素は親コンテナ内で固定されます(親がスクロールアウトすると固定解除)。祖先に overflow: hidden/auto/scroll があると sticky は動作しません。重なり問題を防ぐため常に z-index を設定してください。
/* Sticky header */
.header {
position: sticky;
top: 0;
background: white;
z-index: 100;
padding: 1rem;
}
/* Sticky sidebar */
.sidebar {
position: sticky;
top: 80px; /* offset for fixed header */
height: calc(100vh - 80px);
overflow-y: auto;
}
/* Note: sticky doesn't work if a parent has
overflow: hidden or overflow: auto */