position: absoluteの要素を中央配置にする

position: absoluteの要素を上下や左右の中央位置に配置する方法をメモ。

サンプルコード

まずは左右中央配置です。

<div class="box"></div>

左右中央の場合、leftとrightを0、marginの左右方向をautoに設定します。

.box {
	position: absolute;
	left: 0;
	right: 0;
	margin-inline: auto;
}

左右中央に配置するデモページ

次に上下中央配置です。
topとbottomを0、marginの上下方向をautoに設定します。

.box {
	position: absolute;
	top: 0;
	bottom: 0;
	margin-block: auto;
}

上下中央に配置するデモページ

左右中央配置と上下中央配置を合わせて設定すると、上下左右中央配置になります。

.box {
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	margin: auto;
}

上下左右中央に配置するデモページ

topとbottom、left、rightが同じ値になるので、insetで一括指定でも可能です。

.box {
	position: absolute;
	inset: 0;
	margin: auto;
}

上下左右中央を一括指定するデモページ

absoluteだけではなく、fixedの場合も同様に中央配置にできます。

.box {
	position: fixed;
	inset: 0;
	margin: auto;
}

fixedの場合のデモページ

参考サイト

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2026年3月
1234567
891011121314
15161718192021
22232425262728
293031