MEMO!CSS - 要素のなかのテキストを上下左右中央ぞろえ
こんな感じに100×100のブロックの中央に1行テキストを表示したいです。
ブロックの外側には5pxの余白があります。
その幾つかあるやり方を、まとめてみました。
See the Pen 要素を中央に by hebisan (@climbFrog) on CodePen.
■検証環境
1. margin: auto;
親要素のdivで100x100の領域を確保し、子要素のdivにテキストを設定して中央に揃える。
・親要素 position: relative;
・子要素 position: absolute;
・子要素に、top,right,bottom,leftをauto以外で指定する
・子要素は幅を100%にしてtext-align: center;にすることで左右の中央にした
<div class="base case-mauto-out"> <div class="case-mauto-in">日記</div> </div>
.base { width: 100px; background: #5070B2; border-radius: 4px; color: #FFFFFF; font-size: 14px; } .case-mauto-out { position: relative; height: 100px; margin: 5px; } .case-mauto-in { position: absolute; top: 0; right: 0; bottom: 0; left: 0; height: 1em; width: 100%; text-align: center; margin: auto; }
以下baseクラスは全てに適用する。
2. display: table-cell
display: table-cellにして、text-align: center;で横方向の、vertical-align:middle;で縦方向の中央にする。
・display: table-cellを指定するとmarginで余白をつくることが出来なくなる
・親要素にdisplay: table;を指定し、border-collapse: separate; border-spacing: 5px;で余白を表現する。
<div class="case-table"> <div class="base case-table-cell">日記</div> </div>
.case-table { display: table; border-collapse: separate; border-spacing: 5px; } .case-table-cell { display: table-cell; height: 100px; text-align: center; vertical-align: middle; }
3. paddingで調整
ブロック要素はvertical-alignで縦方向の中央揃えができないので、上下にpaddingを指定することで代替とする
・line-heightでテキストの高さを決め、逆算して余白(上下)の高さを決める
<div class="base case-padding">日記</div>
.case-padding { padding: 40px 0; text-align: center; line-height: 20px; margin: 5px; }
4. display:flex;
※ベンダープレフィックスをつけないとブラウザにより崩れます
<div class="base case-flex">日記</div>
.case-flex { display: flex; height: 100px; margin: 5px; justify-content: center; align-items: center; }
5. ネガティブマージン
親要素から上から50%の位置、左から50%の位置に配置する。
上から50%の位置に文字の中央がくるように、半文字文上にずらす(margin-top: -0.5em)
同様に左からの位置も、文字の半分を左にずらす。今回は2文字固定なので1文字分ずらす(margin-left: -1em)
<div class="base case-negative-out"> <span class="case-negative-in">日記</span> </div>
.case-negative-out { height: 100px; position: relative; margin: 5px; } .case-negative-in { position: absolute; top: 50%; left: 50%; margin-top: -0.5em; margin-left: -1em; }
(byへびさん)