【CSS】sibling-index() / sibling-count()の使い方

どうも、くまだです。

CSSのsibling-index()について。

sibling-index()とは

sibling-index()は、その要素が兄弟の中で何番目かを整数で返すCSS関数です。1から始まります。

コードは以下のようになります。

    <div class="container">
        <div class="box">
            <p>テキストテキスト</p>
        </div>
        <div class="box">
            <p>テキストテキスト</p>
        </div>
        <div class="box">
            <p>テキストテキスト</p>
        </div>
        <div class="box">
            <p>テキストテキスト</p>
        </div>
        <div class="box">
            <p>テキストテキスト</p>
        </div>
        <div class="box">
            <p>テキストテキスト</p>
        </div>
        <div class="box">
            <p>テキストテキスト</p>
        </div>
        <div class="box">
            <p>テキストテキスト</p>
        </div>
    </div>
.container {
  padding: 80px;

}

.box {
  background-color: orange;
  display: inline-block;
  animation: fade-in .6s backwards;
  animation-delay: calc(sibling-index() * .12s);
}


@keyframes fade-in {
  0% {
    opacity: 0;
    transform: translateY(14px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

要素が左から順に、ふわっとアニメーションするような動きになります。

例えば、要素にアニメーションかけるとき、以下のように書くことがありましたが、

.box:nth-child(1) { animation-delay: 0.1s; }
.box:nth-child(2) { animation-delay: 0.2s; }
.box:nth-child(3) { animation-delay: 0.3s; }

sibling-index()を使うと、以下のように書くことができます。

animation-delay: calc(sibling-index() * .12s);

widthのようなプロパティに対しても適用できます。(単位は必要)

.container {
  padding: 80px;
  display: grid;
  row-gap: 20px;

}


.box {
  background-color: orange;
  display: block;
  width: calc(sibling-index() * 56px);
  height: 30px;
}

以下のように色相を等分みたいなこともできます。

.box {
  background-color: orange;
  display: block;
  width: calc(sibling-index() * 56px);
  height: 30px;
  background-color: hsl(calc(360deg / sibling-count() * sibling-index()) 70% 58%);

}

ただし、display:none;で非表示にしてもカウント対象になること、nth-childと同じで要素の種類は問わない、などの制約があります。

ここまで読んでくださりありがとうございました。

この記事を書いた人