テキストを含むdiv要素がありますが、このdivの内容を垂直方向に中央揃えにしたいのです。
これが私のdivスタイルです。
#box {
height: 170px;
width: 270px;
background: #000;
font-size: 48px;
color: #FFF;
text-align: center;
}
<div id="box">
Lorem ipsum dolor sit
</div>
何か良い方法はありますか?
この基本的な方法を試してみてください。
div {
height: 90px;
line-height: 90px;
text-align: center;
border: 2px dashed #f69c55;
}
<div>
Hello World!
</div>
行の高さを包含する box 要素と同じ高さに設定しているため、1 行のテキストに対してのみ動作します。
これは、テキストを垂直に整列させる別の方法です。この方法は、1行のテキストにも複数行のテキストにも対応できますが、固定の高さのコンテナが必要になります。
div {
height: 200px;
line-height: 200px;
text-align: center;
border: 2px dashed #f69c55;
}
span {
display: inline-block;
vertical-align: middle;
line-height: normal;
}
<div>
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Haec et tu ita posuisti, et verba vestra sunt. Non enim iam stirpis bonum quaeret, sed animalis. </span>
</div>
このCSSでは、<div>
のサイズを変更し、<div>
のline-heightをその高さと同じにすることで<span>
を垂直方向に中央揃えにし、<span>
をvertical-align: middle
のインラインブロックにしています。そして、<span>
のline-heightを通常に戻し、その内容がブロック内で自然に流れるようにします。
これは、古いdisplay: tableと
display: table-cell`をサポートしていないブラウザ(基本的にはInternet Explorer 7だけ)では動作しないかもしれませんが、別の方法を紹介します。CSSを使ってテーブルの動作をシミュレートしています(テーブルは垂直方向の配置をサポートしているので)。
div {
display: table;
height: 100px;
width: 100%;
text-align: center;
border: 2px dashed #f69c55;
}
span {
display: table-cell;
vertical-align: middle;
}
<div>
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>
この手法は、要素のtop、bottom、left、rightを0に設定して絶対配置するもので、Smashing Magazineの記事、Absolute Horizontal And Vertical Centering In CSSに詳細が記載されています。
次のようなCSSコードを追加することで、簡単に実現できます。
display: table-cell;
vertical-align: middle;
つまり、あなたのCSSは最終的に次のようになります。
。#box {
height: 90px;
width: 270px;
background: #000;
font-size: 48px;
font-style: oblique;
color: #FFF;
text-align: center;
margin-top: 20px;
margin-left: 5px;
display: table-cell;
vertical-align: middle;
}
<div id="box">
Some text
</div>
1行のテキスト(または1文字)の場合は、このテクニックを使うことができます。
これは、#box
が固定ではなく、相対的な高さを % で指定している場合に**使用できます。
<div id="box"></div>
#box::before {
display: block;
content: "";
height: 50%;
}
#box::after {
vertical-align: top;
line-height: 0;
content: "TextContent";
}
ライブデモはJsBin(CSSの編集が容易)または[JsFiddle][2](結果フレームの高さの変更が容易)でご覧いただけます。
内側のテキストをCSSではなくHTMLで配置したい場合は、テキストコンテンツを追加のinline要素で囲み、それに合わせて#box::after
を編集する必要があります。(そしてもちろん、content:
プロパティは削除すべきです)。
例えば、以下のようになります。
<div id="box"><span>TextContent</span></div>
.
この場合、#box::after
は #box span
に置き換えてください。
Internet Explorer 8をサポートするには、::
を:
に置き換える必要があります。