5
4

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.

CSSだけでグリッドレイアウトの最初の行のみ挙動を変えたい!

Last updated at Posted at 2016-06-10

ブロックの並び

通常、CSSでグリッドレイアウトを用いたブロックを並べる場合は、左から順に配置になります。

image

image

2行以上になる場合は左揃えのほうが整って見える場合が多いのでそれでいいのですが、もし1行で終わるのであれば1行目だけ均等配置、中央揃えなどにしたほうが収まりが良いレイアウトもあると思います。

image

image

しかしながら一体どうやってCSSを書いたらいいでしょうか…JSで数を数えてやるのが早い気がしますが…
ECサイトを作成してて、商品一覧で1点〜数点しかない場合、なんとなく中央もしくは均等配置のほうが収まりがいい気がしてきたので、できないかなーと思ったらできました。

Flexboxでできた

Change first row by flexbox

いろいろやったら出来たので、CodePenにアップしてみました。
カラム数やボックスの量などを調節できるようにしてあります。

flexboxで一旦並べ、最初の行をnth-of-typeで制御するといった手法です。
marginとの合わせ技で1行目のみ均等・中央揃えが再現できました。
たぶんJS使わずに共通クラスのみでやる場合、Flexboxを用いるしかやりようがないような気がします。

コード

重要な部分の抜粋


.list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin: $gutter*2 $gutter*-1 0;
  
  &.is-start {
    justify-content: flex-start;
  }
}

.list__item {
  box-sizing: border-box;
  flex-basis: calc(100% / #{$columns});
  height: 300px;
  margin-bottom: $gutter*2;
  padding: 0 $gutter;
  
  .is-justify & {
     &:nth-of-type(-n+#{$columns}) {
      margin: 0 auto $gutter*2;
    }

    &:nth-of-type(n+#{$columns}):last-of-type {
      margin-right: auto;
    }
  }
  
  .is-center & {
    &:nth-of-type(-n+#{$columns}) {
      margin: 0 0 $gutter*2;
    }
    
    &:first-of-type {
      margin-left: auto;
    }
    
    &:nth-of-type(n-#{$columns}):last-of-type {
      margin-right: auto;
    }

  }
  
}

キモはmarginにautoをかけるところだと思います。
1個しかない場合はonly軍団を使っていろいろやるとか、そんなこともFlexboxだったら簡単にできそうですね。
レスポンシブでも大丈夫なので、ブラウザ幅に応じてカラム数を増やしたり減らしたりなどしても真ん中や均等に配置できるのでECサイトとかだと使えそうです。
高さも揃えられるしFlexboxは本当に便利。
とりあえずChrome、Firefox、Safari、Edgeで確認したのでモダンブラウザ対応でOKであればいろいろ使えそうです。
IE9以下はもういいんじゃあないでしょうか :innocent:

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?