【div】段組みをレスポンシブ対応させるCSSのサンプルコード

段組レイアウトをレスポンシブ対応させるCSS設定として、tableのtrやtdをdisplay: blockでwide: autoにする方法をご紹介しましたが、今回はもっとシンプルな、divタグで組んだ段組にCSSを設定して、PCで横並びのレイアウトを、スマホ(画面の幅480px以下)で縦並びにする方法をご紹介します。

デモ

ボックス1
ボックス2
ボックス3

CSS+html

<!-- CSS -->
<style type="text/css">
<!--
*, *:before, *:after {-moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;}/*ボーダーを内側に*/
.box {display: inline-block;width: 30%;border: 5px solid #ccc;margin: 0 5px 0 0;padding: 1em;}/*各ボックス幅を30%に、ボーダーの線幅を5px*/
@media only screen and (max-width:480px) {
.box {display: block;width: 100%;margin: 0 0 5px 0;}
}/*画面の幅が480px以下になるとblock要素になり縦並びに*/
-->
</style>
<!-- html -->
<div class="box">ボックス1</div>
<div class="box">ボックス2</div>
<div class="box">ボックス3</div>

特定の要素(div)への指定は、以下をお使いください。
一番最初、div.box:first-child{ }
一番最後、div.box:last-child{ }
偶数番目、div.box:nth-child(odd){ }
奇数番目、div.box:nth-child(even){ }
上からn番目、div.box:nth-child(n){ }
下からn番目、div.box:nth-last-child(n){ }

タイトルとURLをコピーしました