LoginSignup
3
3

More than 3 years have passed since last update.

【CSS】Flexboxの折返し配置、1つのときだけ真ん中にする方法

Last updated at Posted at 2019-05-20

要件

Flexboxの折返しリストにおいて、リストアイテムが一つしかなかった場合、Flexboxデフォルトの左寄せではなく中央寄せにしたいデザインがあった。
qiita.jpg

コード

pug

.bg
  section
    h2 wrap(1)
    .wrap
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")

  section
    h2 wrap(2)
    .wrap
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")

  section
    h2 wrap(3)
    .wrap
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")

  section
    h2 wrap(4)
    .wrap
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")
      .itemWrap
        img.item(src="https://placehold.jp/150x150.png")

scss

// 装飾
.bg {
  color: #fff;
  background: #444;
  max-width: 600px;
  margin: 0 auto;
}
section {
  margin-bottom: 80px;
}
.item {
  width: 100%;
  display: block;
}

//メイン
.wrap {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -20px;
}
.itemWrap {
  box-sizing: border-box;
  flex-basis: 50%;
  padding: 20px;
   &:first-child {
    margin-right: auto;
    margin-left: auto;
  }
}

解説

基本

以前、紹介した余白をスマートに記述する方法を用いている。
https://qiita.com/dorara/items/89364b0ab9e9d5d5c7b7

flexをかける外側wrap

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

paddingを用いて余白を確保するので、justify-contentはデフォルトのまま。
flex-wrapの折り返しon。(デフォルトがoff
横paddingを打ち消すためのマイナスマージン。

アイテム各々のwrapper

.itemWrap {
  box-sizing: border-box;
  flex-basis: 50%;
  padding: 20px;
}

Flexのためのdiv。アイテム(今回は画像)を囲い、幅の%指定とpaddingで余白確保を行う。
片方のpadding-left + もう片方のpadding-right でアイテム横間の余白を作るので、paddingの値は間の距離/2。

最初だけmargin:auto


 &:first-child {
    margin-right: auto;
    margin-left: auto;
  }

そして、 itemWrap の一番目だけ左右のmarginをautoに設定する。

2個以上の場合は、wrapの要素をitemWrapの幅がぴったり覆っているので、margin:autoは発動せず、1個単体のときのみセンタリングする仕組み。

実装サンプル

3
3
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
3
3