【CSS】子要素の数が偶数か奇数かでデザインを変える

やりたいこと

子要素の数に応じてデザインを変えられるよう、セレクタを設定する。

子要素の数が「偶数/奇数」の場合や「Nの倍数」の時などを想定。

やりかた

「:has()」「:nth-child()」「:last-child」を組み合わせて使います。

最後の子要素が特定の条件に当てはまるかを判定します。
例として子要素が「2の倍数(偶数)の場合は赤」「3の倍数の場合は青」「2の倍数かつ3の倍数の場合は紫」のCSSを記載します。

HTML

<div class="csstest">
	<ul>
		<li>1</li>
	</ul>
	<ul>
		<li>1</li>
		<li>2</li>
	</ul>
	<ul>
		<li>1</li>
		<li>2</li>
		<li>3</li>
	</ul>
	<ul>
		<li>1</li>
		<li>2</li>
		<li>3</li>
		<li>4</li>
	</ul>
	<ul>
		<li>1</li>
		<li>2</li>
		<li>3</li>
		<li>4</li>
		<li>5</li>
	</ul>
	<ul>
		<li>1</li>
		<li>2</li>
		<li>3</li>
		<li>4</li>
		<li>5</li>
		<li>6</li>
	</ul>
</div>

CSS

.csstest > ul:has(>*:nth-child(2n):last-child){
	background: red;/*2の倍数なので赤*/
}
.csstest > ul:has(>*:nth-child(3n):last-child){
	background: blue;/*3の倍数なので青*/
}
.csstest > ul:has(>*:nth-child(2n):nth-child(3n):last-child){
	background: purple;/*2の倍数かつ3の倍数なので紫*/
}

結果

  • 1
  • 1
  • 2
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

コメント

タイトルとURLをコピーしました