【HTML/CSS】モダン中央揃え3選
CSSを使ったモダンな要素の中央揃えの手法を3つ紹介します。
忙しい人の為に
See the Pen zYNVRgQ by Yuki Ishii (@yukiishii) on CodePen.
はじめに
中央揃えさせる要素は下記のHTMLのように親要素があり子要素が1つの場合です。
子要素が複数ある場合は予想と違う結果が出る可能性があります。
またテキストやボタンなど行のみを中央揃えしたい場合はまた別の手法が有効となります。
<h1>No centralized</h1>
<div class="container">
<div class="child">
Child
</div>
</div>
displary: grid; で中央揃え
一番コードが短くてすむ手法です。
.container {
/* Following code makes centralizing */
display: grid;
place-items: center;
}
.child {}
display: flex; で中央揃え
Gridを使用したものより1行コードが増えますが多用されている手法です。
.container {
/* Following code makes centralizing */
display: flex;
justify-content: center;
align-items: center;
}
.child {}
position: absolute; で中央揃え
先に紹介した手法とは別で子要素自体にスタイリングをしポジションを移動させます。
親要素をposition: relative;にする必要があります。
.container {
/* Need parent a relative position */
position: relative;
}
.child {
/* Following code makes centralizing */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
終わりに
今回手段のみを紹介しましたが、理由や仕組みなどは他の記事で紹介したいと思います。
今すぐ気になる方はご連絡ください。
Author And Source
この問題について(【HTML/CSS】モダン中央揃え3選), 我々は、より多くの情報をここで見つけました https://qiita.com/YukiIshii10/items/30009bc9e76b9df9d076著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .