[CSS]2行以上あるテキストを上下中央に配置する

画像の隣にテキスト、というのではなくて文章だけの場合です。
テキストが一行ならline-heightでおkだけど、行が複数あった場合はどうする?

Vertical Centering

テーブル使えば一発だけどdivでやろうとすると結構面倒くさい。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>Vertical Centering Text in DIV</title>
		<style>
			.centering {
				display: table;
				height: 300px;
				width: 300px; 
				background: #efefef;
				overflow: hidden;
			}
			.centering-body {
				display: table-cell;
				vertical-align: middle;
			}
		</style>
		<!--&#91;if lt IE 8 &#93;>
		<style>
			.centering {
				position: relative;
			}
			.centering-body {
			 	 position: absolute;
				 top: 50%;
			}
			.centering-body div {
			 	position: relative;
				top: -50%;
			}
		</style>
		<!&#91;endif&#93;-->
</head>
	<body>
<div class="centering">
	<div class="centering-body">
		<div><p>et Aenean Vestibulum morbi tristique netus Donec vitae, quam sit Pellentesque eleifend libero ultricies amet placerat Mauris vitae est. ac eu ante. tempor et feugiat egestas. semper. fames amet, malesuada tortor mi egestas sit turpis quam, eget, habitant leo. ultricies senectus </p></div>
	</div>
</div>
	</body>
</html>

各要素にborderを表示すると分かりやすい。

Vertical Centering [border]

モダンブラウザはdisplay:table-cellとvertical-align: middleで一発です。

IE7以下
IE7以下はdisplay:table-cell未対応なのでpositionを使う。
一番親になる要素(div.centering)をposition:relativeにすると、子要素のpositionプロパティをstatic以外の値にした場合に親の左上を基準とします。
長子要素のdiv.centering-bodyをposition:absoluteにしてtop:50%にすると
ちょうど親要素の中心線がdiv.centering-bodyのy=0の位置になるわけです。
その上で、中央に配置したい要素(div.centering-body div)を親要素の中心から-50%上に移動させれば、
きっちり上下中央になる、という仕掛けです。

色々試してみたんだけど、ハックよりif使う方がスマートらしかった。

Javscript
display: table-cell対応している場合は枠になる要素が1つだけでいいので
IE7以下の場合のみposition用のdiv要素を追加すればDIVまみれになることは避けられるんじゃないかなー

コメントを残す

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください