display:table が便利なのでメモです!
ie8以上対応だし。
普段はフロートしてるけど
アイコンなど子要素を上下や左右中央揃えなど
整列しつつフロートしたい時などに重宝します。
1,基本形
親にdisplay: table;
子(セル)にdisplay: table-cell;
が基本です!
vertical-align: middle; /* この指定で上下中央揃え */
hoge
<div class="table">
<p class="cell">
<img src="img1.png">
</p>
<p class="cell">
<img src="img1.png">
</p>
<p class="cell">
<img src="img1.png">
</p>
</div>
<style>
.table{
width: 500px;
display: table;
/* 隣接するセルのボーダーを重ねて表示します。*/
border-collapse: collapse;
}
.cell{
display: table-cell;
padding: 10px;
border: 1px solid #333;
text-align: center; /* この指定で左右中央揃え */
vertical-align: middle; /* この指定で上下中央 */
}
</style>
2、特定のセルのサイズ固定したい
完成図
親の500pxに対して
最初のセルだけ250pxと指定すると
そこは確保され、あとは均等に配分されます。
hoge
<div class="table">
<p class="cell first_cell">
<img src="img1.png">
</p>
<p class="cell">
<img src="img1.png">
</p>
<p class="cell">
<img src="img1.png">
</p>
</div>
<style>
.table{
width: 500px;
display: table;
border-collapse: collapse;
}
.cell{
display: table-cell;
padding: 10px;
border: 1px solid #333;
text-align: center; /* この指定で左右中央揃え */
vertical-align: middle; /* この指定で上下中央 */
}
.first_cell{
width: 250px;
}
</style>
3、子要素の内容が違えど、幅を揃えたい
display: table;を設定した親に、
table-layout:fixed; を指定
でいけました。
hoge
<div class="table">
<p class="cell">
<img src="img1.png"><br>
あああああああああああああああああああああ
</p>
<p class="cell">
<img src="img1.png">
</p>
<p class="cell">
<img src="img1.png">
</p>
</div>
<style>
.table{
width: 500px;
display: table;
border-collapse: collapse;
table-layout:fixed; /* これが肝 */
}
.cell{
display: table-cell;
padding: 10px;
border: 1px solid #333;
text-align: center; /* この指定で左右中央揃え */
vertical-align: middle; /* この指定で上下中央 */
}
</style>
参考 [CSS] display:tableを学ぶ
http://www.yoheim.net/blog.php?q=20150102