divタグでvertical-align/divタグを縦中央に寄せる

HTML5の内容ではないのですが、HTMLとHTML5でタグを分けるのは面倒だったので、HTML5タグでこのエントリー書きます。

最近、仕事でHTMLを書き始めたのですが、divタグを中央に寄せたり、縦軸の中央に寄せるところではまったのでそのメモを。

divタグ内を中央寄せ

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no">
<title>中央寄せテスト</title>
<style type="text/css">
.test1 {
width:80%;
background-color:green;
}

.test2 {
width:80%;
background-color:red;
margin:0 auto;
}
</style>
</head>
<body>
<div class="test1"><h1>test1</h1></div>
<div class="test2">
<div class="test2"><h1>test2</h1></div>
</div>
</body>
</html>
</html>


marginの横幅を、autoにすれべ良いみたいですね。

■参考サイト
CSSで中央配置(センターリング)する方法

divタグでvertical-align

まずは、以下のサンプルを見てください。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no">
<title>divのvertical-alignテスト</title>
</head>
<style type="text/css">
.table_cell_1,
.table_cell_2,
.table_cell_3 {
 height:100px;
 vertical-align:middle;
}

.table_cell_1 {
background-color:red;
}

.table_cell_2 {
background-color:green;
}

.table_cell_3 {
background-color:blue;
}

</style>
<body>
<div class="table">
<div class="table_cell_1">
table_cell_1
</div>
<div class="table_cell_2">
table_cell_2
</div>
<div class="table_cell_3">
table_cell_3
</div>
</div>
</body>
</html>

↑このように、div内の文字を縦軸の真ん中にしようとしても、vertical-alignがうまく動かないため、左上によって表示されてしまいます。


そんなときは、以下のように、display:table; display:table-cell を使用すると、vertical-alignを使用できるようになります。なお、float-leftを使用すると、無効になってしまようなので、注意してくださいmm

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no">
<title>divのvertical-alignテスト</title>
</head>
<style type="text/css">

.table {
 width:100%;
 display:table;
}

.table_cell_1,
.table_cell_2,
.table_cell_3 {
 display:table-cell;
 height:100px;
}

.table_cell_1 {
background-color:red;
vertical-align:top;
}

.table_cell_2 {
background-color:green;
vertical-align:middle;
}

.table_cell_3 {
background-color:blue;
vertical-align:bottom;
}

</style>
<body>
<div class="table">
<div class="table_cell_1">
table_cell_1
</div>
<div class="table_cell_2">
table_cell_2
</div>
<div class="table_cell_3">
table_cell_3
</div>
</div>
</body>
</html>




■参考サイト
tableを使わずdivで縦位置を指定