13
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?

【CSS】兄弟要素の位置や合計数に基づいたスタイルを作る

Last updated at Posted at 2025-06-28

はじめに

みなさんは、兄弟要素の位置や合計数に基づいたスタイルにしたいとおもったことはあるでしょうか?

  • 兄弟要素の順番に応じて、WidhtやColorを変更したい
  • 兄弟要素の合計数に応じて、WidhtやColorを調整したい

実は、Chrome138 から、兄弟要素の位置や合計数に基づいたスタイルにできる関数 sibling-index()sibling-count() が使えるようになりました。

そのため、この記事は sibling-index()sibling-count() の使い方を紹介します。

sibling-index() とは?

sibling-index()は、兄弟要素の中で何番目かを取得できる CSS 関数です。
indexは、1から始まります。

sample.css
.sample {
  width: calc(75px * sibling-index());
}

See the Pen sibling-index() by degudegu2510 | Qiita (@degudegu2510) on CodePen.

サンプル:兄弟要素の順番に応じて色を変えたい。

こんな感じにグラデーションを表現するのが簡単になっています。

See the Pen sibling-index() by degudegu2510 | Qiita (@degudegu2510) on CodePen.

sibling-count() とは?

sibling-count() は、兄弟要素の合計数が取得できる CSS 関数です。

sample.css
.sample {
  width: calc(100% / sibling-count());
}

See the Pen sibling-index() by degudegu2510 | Qiita (@degudegu2510) on CodePen.

サンプル:アニメーションディレイを要素数で変える

See the Pen sibling-count() - animation by degudegu2510 | Qiita (@degudegu2510) on CodePen.

まとめ

この記事では、兄弟要素の位置や合計数に基づいたスタイルを作れる sibling-index()sibling-count() を紹介しました。

sibling-index()sibling-count() でさらに、CSSだけでリッチなロジックが書ける時代がどんどん近づいてきているようにかんじます。


最後まで読んでくださってありがとうございます!

普段はデザインやフロントエンドを中心にQiitaに記事を投稿しているので、ぜひQiitaのフォローとX(Twitter)のフォローをお願いします。

13
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
13
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?