今回は absolute を使用してボックス要素を上下中央に配置します。
失敗例
HTML
<div class="container">
<div class="box"></div>
</div>CSS
.container {
position: relative;
width: 100vw;
height: 100vh;
background-color: #99cc00;
}
.box {
position: absolute;
background-color: #f53838;
height: 100px;
width: 100px;
top: 50%;
left: 50%;
}結果
解説
top、left を 50% 指定するだけだと、boxクラス(ブロック要素)の左上角が上下中央になるので、boxクラスが中央になりません。
成功例
HTML
<div class="container">
<div class="box"></div>
</div>CSS
.container {
position: relative;
width: 100vw;
height: 100vh;
background-color: #99cc00;
}
.box {
position: absolute;
background-color: #f53838;
height: 100px;
width: 100px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}translate を指定し、boxクラスの大きさ半分についてXおよびYの位置(左上角の位置)をずらす事で文字が中央になります。
translateについては以下を参考にして下さい。
結果
定番
HTML
<div class="container">
<div class="box"></div>
</div>CSS
.container {
position: relative;
width: 100vw;
height: 100vh;
background-color: #99cc00;
}
.box {
position: absolute;
background-color: #f53838;
height: 100px;
width: 100px;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}結果
最後に
特にありません。