divを横並びにする

divを横並びにする

自分のやり方
正規のやり方かどうかはわからないけどできたのでメモ

index.html

<html>
<head>
   <meta charset="UTF-8">
   <title>Document</title>
   <link rel="stylesheet" href="css/style.css">
</head>
<body>
        <div class="a">
            <div class="b"></div>
            <div class="c"></div>
        </div>
</body>
</html>

style.css

html, body{
    width: 100%;
}
.a{
    width: 100%;
    height: 60px;
}
.b{
    width: 50%;
    height: 100%;
    background-color: red;
}
.c{
    width: 50%;
    height: 100%;
    background-color: blue;
}

htmlbodyに対してのwidth: 100%;は他で%を使うために指定してる

このまま表示

f:id:seto_abe:20161207140152p:plain

2段で表示されちゃうのでこれを横並びに

display: table;を使う

display: table;display: table-cell;を挿入

style.css

html, body{
    width: 100%;
}
.a{
    width: 100%;
    height: 60px;

    display: table;
}
.b{
    width: 50%;
    height: 100%;
    background-color: red;

    display: table-cell;
}
.c{
    width: 50%;
    height: 100%;
    background-color: blue;

    display: table-cell;
}

position: absolute;を使う

以下のようにコードを追加する

style.css

html, body{
    width: 100%;
}
.a{
    width: 100%;
    height: 60px;

    position: relative;
}
.b{
    width: 50%;
    height: 100%;
    background-color: red;

    position: absolute;
    top: 0;
    left: 0;
}
.c{
    width: 50%;
    height: 100%;
    background-color: blue;

    position: absolute;
    top: 0;
    right: 0;
}

この2つのやり方でできたけど個人的にはposition: absolute;の方が使い勝手がよい

重ねて表示させたり上下左右中央表示にするときにも使える