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;
}
コメントが承認されるまで時間がかかります。