ボックスモデル
CSS
margin、padding、border、box-sizing
ボックスモデルの基本
content、padding、border、margin
/* ボックスモデルの構成 */
/* [margin][border][padding][content][padding][border][margin] */
.box {
/* コンテンツ */
width: 300px;
height: 200px;
/* パディング: 内側の余白 */
padding: 1rem; /* 全方向 */
padding: 1rem 2rem; /* 上下 左右 */
padding: 1rem 2rem 1rem 2rem; /* 上 右 下 左 */
padding-top: 0;
/* ボーダー */
border: 1px solid #e5e7eb;
border-top: 2px solid #10b981;
border-radius: 8px; /* 角丸 */
border-radius: 50%; /* 円形 */
/* マージン: 外側の余白 */
margin: 1rem auto; /* 水平中央揃え */
margin-bottom: 2rem;
}
/* box-sizing の違い */
.default { box-sizing: content-box; } /* width = コンテンツのみ */
.border { box-sizing: border-box; } /* width = コンテンツ+padding+border */
/* グローバルにborder-boxを設定(推奨) */
*, *::before, *::after { box-sizing: border-box; }displayプロパティ
block、inline、inline-block、none など
/* block: 幅いっぱいに広がる、前後に改行 */
.block { display: block; }
/* 例: div, p, h1-h6, section, article, ul, li */
/* inline: コンテンツの幅のみ、改行なし */
.inline { display: inline; }
/* 例: span, a, strong, em — width/height は無効 */
/* inline-block: inline のように並ぶが width/height が有効 */
.inline-block { display: inline-block; }
/* none: 表示しない(スペースも消える) */
.hidden { display: none; }
/* visibility: hidden と違い スペースが残る */
.invisible { visibility: hidden; }
/* contents: 自身のボックスを消し子要素を直接表示 */
.wrapper { display: contents; }
/* table系 */
.table { display: table; }
.table-row { display: table-row; }
.table-cell{ display: table-cell; vertical-align: middle; }positionプロパティ
static、relative、absolute、fixed、sticky
/* static: デフォルト。通常のフロー */
.static { position: static; }
/* relative: 通常位置から相対移動(スペースは保持) */
.relative {
position: relative;
top: 10px;
left: 10px;
z-index: 1;
}
/* absolute: 最近の位置付け祖先を基準に配置 */
.parent { position: relative; }
.absolute {
position: absolute;
top: 0;
right: 0;
/* 親の右上に配置 */
}
/* fixed: viewportを基準に配置(スクロールしても固定) */
.fixed {
position: fixed;
bottom: 1rem;
right: 1rem;
z-index: 1000;
}
/* sticky: スクロール位置に応じてrelative↔fixed切り替え */
.sticky {
position: sticky;
top: 0; /* スクロール時にここで固定 */
z-index: 50;
}overflow と visibility
コンテンツのはみ出しと表示制御
/* overflow */
.box {
overflow: visible; /* はみ出して表示(デフォルト) */
overflow: hidden; /* はみ出しを切り取る */
overflow: scroll; /* 常にスクロールバー表示 */
overflow: auto; /* 必要な時のみスクロールバー */
overflow-x: hidden;
overflow-y: auto;
/* テキストの省略表示 */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; /* 末尾に「...」 */
}
/* 複数行の省略(WebKit系) */
.clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
/* aspect-ratio */
.video-wrapper {
aspect-ratio: 16 / 9;
width: 100%;
}