≪ Today I learned. RSS購読
公開日
タグ
CSS
著者
ダーシノ

Quantity Queriesで要素数ごとに表示を切り替える

Quantity Queriesとは、「特定の要素がいくつあるか?」によってスタイルを切り替えるテクニックを指す。

たとえば、Gridレイアウトにおいて要素数によって以下のようにスタイルを変えたいことがある。


要素:1つ
+---------------+
|               |
+---------------+

要素:2つ
+------+ +------+
|      | |      |
+------+ +------+

要素:3つ
+------+ +------+
|      | |      |
+------+ +------+
+---------------+
|               |
+---------------+

要素:4つ
+------+ +------+
|      | |      |
+------+ +------+
+------+ +------+
|      | |      |
+------+ +------+

:has():nth-child()を組み合わせることで、要素数に応じたスタイル変更ができる。

<section class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  ...
</section>
/* 要素が2個の場合 */
.container:has(> :nth-child(2):last-child) {
  ...
}

/* 要素が2個以上の場合 */
.container:has(> :nth-child(2)) {
  ...
}

/* 要素が3個以上の場合*/
.container:has(> :nth-child(3)) {
  ...
}

/* 要素が4個の場合 … 要素2個の場合と同じ */

/* 要素が5個の場合(≒5以上、7未満) */
.container:has(> :nth-child(5)):not(:has(> :nth-child(7))) {
  ...
}

/* 要素が少なくとも6個以上の場合 */
.container:has(> :nth-child(6)) {
  ...
}

/* 要素が7個以下の場合 */
.container:has(> :last-child:nth-child(-n + 7)) {
  ...
}

/* 要素が2以上、5以下の場合 */
.container:has(> :nth-child(2):nth-child(-n + 4)) {
  ...
}

デモ

1