A setting that decides where an element is placed—whether it stays in the normal flow, shifts a little, sticks to the screen, or snaps in place while scrolling.
positionプロパティは、要素を通常の流れのままにするか、少しずらすか、親や画面を基準に好きな場所へ置くか、スクロールで貼り付けるかを選ぶための設定です。
CSS
○○ {position: 値;}
○○にはセレクタが入ります。値には次の5つのどれかを指定します。
top: 0;
)に達するとその位置に貼り付きます。top/left などのオフセット指定が必要です。 position で決めるのは「配置方法(基準)」です。実際の表示位置は top
/ right
/ bottom
/ left
(まとめて指定できる略記 inset
)で調整します。
static
以外のときです。z-index
で調整します(static
には基本的に効きません)。重なり順は z-index
で調整します(基本は position
を static
以外にして使います)。思ったように前面に来ない場合は、対象(または親)に position: relative;
を付けてから z-index
を指定してみてください。
例えば、class名が "test" の要素の相対的な位置を指定したいときには、
CSS
.test {position: relative;}
という書き方をします。
Example: 親 relative × 子 absolute(右下にバッジ)
HTML
<div class="card">
バナー
<button class="badge">NEW</button>
</div>
CSS
.card {
position: relative;
width: 240px;
height: 120px;
background: #eee;
}
.badge {
position: absolute;
right: 8px;
bottom: 8px;
}
Example: inset(上下左右を一括指定)
CSS
.fill {
position: absolute;
inset: 0;
}
Example: 画面右下の固定ボタン
CSS
.floatBtn {
position: fixed;
right: 16px;
bottom: 16px;
}
Example: sticky ヘッダー
CSS
.siteHead {position: sticky; top: 0;}
Tips : sticky が効かないときのチェック
overflow: hidden/auto/scroll
があると、その内側だけで貼り付きます。top
などのオフセット指定が必要です(例:top: 0;
)。