CSSで中央寄せにする方法まとめ(Flexbox、transform編)
CSSでの中央寄せのやり方を紹介します。今回はFlexbox、transform編です!ぜひ、前記事と合わせてお読みください。
CSSの中央寄せでつまずいた経験、みなさんありますよね…?
こちらの記事「CSSで中央寄せにする方法まとめ」を見に来てくださる方が多かったので、つまづいてる人も多いんだと思います><
やり方もいっぱいあって、状況によってやり方も変わりますし。最近では、flexboxもよく見るようになりましたよね。
ということで、先ほどの記事に追加という形で、紹介していきます♪
Flexboxを使った中央寄せ
Flexboxなら、CSSの量も少なく、インライン要素もブロック要素でもOK!
また、中央に寄せたい要素のwidth指定がなくても使えるため、レスポンシブしやすいです。
注意点としては、flexboxのプロパティを使う場合は、diplay:flex;を親要素にかける必要があること。 また、IE10までの古いブラウザなどは非対応になります。
ボックスを中央寄せ
<div class="wrap">
<div class="centerBox"></div>
</div>
<style>
.wrap{
display: flex;
justify-content: center;
}
/* ボックス */
.wrap .centerBox{
width: 100px;
height: 150px;
background-color: hotpink;
}
</style>
テキストの中央寄せ
<div class="wrap">
<p class="txt">中央寄せ</p>
</div>
<style>
.wrap{
display: flex;
justify-content: center;
}
/* テキスト */
.wrap .txt{
color: hotpink;
}
</style>
中央寄せ
上下中央にする(おまけ)
<div class="wrap">
<div class="centerBox"></div>
</div>
<style>
.wrap{
/* 枠 */
height: 200px;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.wrap .centerBox{
width: 100px;
height: 100px;
background-color: hotpink;
}
</style>
transformを使った中央寄せ
こちらも、インライン要素、ブロック要素どちらでもOK!
また、中央に寄せたい要素のwidth指定がなくても使えるため、使いやすいのですが、親要素のサイズ幅を超えるとはみ出してしまうので気をつけてくださいね。
今までpositionを使った中央寄せは、要素のwidthの半分を計算してmargin-leftなどで寄せていましたが、transformを使うことで、同じことが簡単にできます。
ボックスを中央寄せ
<div class="wrap">
<div class="centerBox"></div>
</div>
<style>
.wrap{
/* 枠 */
height: 150px;
width: 100%;
position: relative;
}
/* ボックス */
.wrap .centerBox{
position: absolute;
top: 0;
left: 50%;
transform: translate(-50% , 0);
width: 100px;
height: 100px;
background-color: orange;
}
</style>
ボックスを上下中央にする(おまけ)
<style>
.wrap{
position: relative;
height: 200px;
width: 100%;
}
/* ボックス */
.wrap .centerBox{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% , -50%);
width: 100px;
height: 100px;
background-color: orange;
}
</style>
最後に
やり方もいろいろありますが、その時の状況によって合っているやり方を考えるのが大切です。
PC用、SP用、もしくはレスポンシブが必要なのか・・・という部分も含め、わからないときは実際に試しながらやってみましょう♪

