かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

CSS リストをいい感じに折り返す横並びにしたい

リストの間隔は gap で指定したい場合、flex だと各アイテムの width を設定しなければならず面倒

flex

例えば上記の画像のように gap: 24px で 3つ並びにしたいと思った場合、リストアイテムの width を 33.333% にするとアイテム間の間隔分が足らず 100% を超えてしまうので 2 つで折り返してしまう。 この程度のことに calc を使うのも計算量が増えるので避けたい

grid を使って折り返しのあるリスト表示を実現する

.list {
  display: grid;
  grid-auto-flow: row;
  grid-template-columns: repeat(3, auto);
  gap: 24px;
}

grid-template-columnsrepeat を使うことで同じ感覚で自動的に折り返すグリッドを作ることができる

repeat(repeat count, tracks)

  • repeat count: the first argument specifies the number of times that the track list should be repeated. It is specified with an integer value of 1 or more, or with the keyword values auto-fill or auto-fit. These keyword values repeat the set of tracks as many times as is needed to fill the grid container.
  • tracks: the second argument specifies the set of tracks that will be repeated. Fundamentally this consists of one or more values, where each value represents the size of that track. Each size is specified using either a <track-size> value or a <fixed-size> value. You can also specify one or more line names before or after each track, by providing <line-names> values before and/or after the track size.

cf. repeat() - CSS: Cascading Style Sheets | MDN

tracks を 1セットとして repeat count 分で折り返す
grid-template-columns: "repeat(3, auto)"width: auto な要素を 3 つづつで折り返すの意味となる。
要素の幅を等幅にするなら "repeat(3, 1fr)" とすればよい。アイテム数が少なくても 3 つに固定したい場合はシンプルに grid-template-columns: 1fr 1fr 1fr; としてもよい。

この方法の注意点としては、要素が repeat count 以下であっても gap 分の余白が生まれてしまうので、横幅が 100% にはならない可能性がある

Sample

See the Pen Auto wrap list by Grid by KIKIKI (@kikiki_kiki) on CodePen.

↑ item 数を 2 以下にすると右にスペースが残るのが分かる

おわり


[参考]