LoginSignup
10
9

More than 5 years have passed since last update.

display: table;が便利! 子要素を整列しつつフロートしたい時。

Posted at

display:table が便利なのでメモです!
ie8以上対応だし。

普段はフロートしてるけど
アイコンなど子要素を上下や左右中央揃えなど
整列しつつフロートしたい時などに重宝します。

1,基本形

スクリーンショット 2015-12-21 16.23.01.png

親に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、特定のセルのサイズ固定したい

完成図

スクリーンショット 2015-12-21 17.16.53.png

親の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、子要素の内容が違えど、幅を揃えたい

スクリーンショット 2015-12-21 17.18.39.png

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

10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9