0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[自分用メモ]面倒な計算不要!楽チン要素の横並び

Last updated at Posted at 2019-10-05

1列●個の要素を横並びにしたいとき、widthが・・・、marginが・・・と面倒な計算をすることなく、カンタンにレスポンシブ対応の横並びが組める方法をメモ。

例えば1列2個の場合

html

    <div class="itemBox">
      <div class="itemBox__inner">

        <div class="item">
          <div class="itemInner">ITEM</div>
        </div>
        <div class="item">
          <div class="itemInner">ITEM</div>
        </div>
        <div class="item">
          <div class="itemInner">ITEM</div>
        </div>
        <div class="item">
          <div class="itemInner">ITEM</div>
        </div>
        <div class="item">
          <div class="itemInner">ITEM</div>
        </div>
        <div class="item">
          <div class="itemInner">ITEM</div>
        </div>
        <div class="item">
          <div class="itemInner">ITEM</div>
        </div>

      </div>
    </div>

css

*, *:before, *:after {
  -webkit-box-sizing: border-box; 
  box-sizing: border-box;  
}
.itemBox {
  width: 900px;
  margin: 20px auto;
}
.itemBox__inner {
  display: flex; 
  flex-wrap: wrap;   
  margin: 0 0 0 -60px; 
}
.item {
  width: 50%;
  padding: 0 0 60px 60px;
}
.itemInner {
  color: #FFF;
  height: 200px;
  padding: 20px;
  background-color: #444;
}

ポイント

1. box-sizing: border-box;

box-sizing: border-boxで、paddingとborderを幅(width)と高さ(height)に含めることができる。
paddingを要素と要素の余白として考える。
上記の例でいうとココ

.item {
  width: 50%;
  padding: 0 0 60px 60px;
}

figure.png

1列2個並び・・・ 50%
1列3個並び・・・ 33.3%
1列4個並び・・・ 25%
1列5個並び・・・ 20%

box-sizing: border-boxについては、この記事にわかりやすく書かれている。
https://saruwakakun.com/html-css/reference/box-sizing

2. 横並びさせたい要素の直上にひと工夫

上記の例でいうとココ

.itemBox__inner {
  display: flex;  
  flex-wrap: wrap;   
  margin: 0 0 0 -60px; 
}

display: flex;

直下のすべての要素を横並びします。
float: leftは不要。

flex-wrap: wrap;

子要素が100%を超えた場合に折り返すようになる。

margin: 0 0 0 -60px;

.itemの左padding60px分のズレを戻す。

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?