「position: fixed」は、HTML要素を固定位置に配置するために使用されるCSSプロパティです。これを使用すると、要素が画面上からスクロールしなくなり、常に同じ位置に表示されます。「position: fixed」を使用して、HTML要素を中央寄せする方法は次のとおりです。
1.要素に「position: fixed」を設定します。
.center {
position: fixed;
}
2.要素の左右中央に配置するために、「left: 50%」「margin-left: -(要素の幅÷2)」を設定します。
.center {
position: fixed;
left: 50%;
margin-left: -(width of the element)/2;
}
3.要素の上下中央に配置するために、「top: 50%」「margin-top: -(要素の高さ÷2)」を設定します。
.center {
position: fixed;
left: 50%;
margin-left: -(width of the element)/2;
top: 50%;
margin-top: -(height of the element)/2;
}
これで、HTML要素は左右、上下中央に配置されます。
注意:上記の方法で、要素の width, height の値が必要。
要素が固定サイズである場合は明示的にwidth, heightを指定する。もし動的に変化する場合、JavaScriptなどで取得して適用する必要がある。