LoginSignup
1

More than 1 year has passed since last update.

nth-childとは

Posted at

nth-childとは

複数ある要素のうち、ある特定の要素を指定したい場合に使用する。

:例

index.html
    <h2>:nth-childについて</h2>
    <div>
        <span>Item 1</span>
        <span>Item 2</span>
        <span class="cls">Item 3</span>
        <span>Item 4</span>
        <span>Item 5</span>
    </div>
style.scss
div{
  & span{
    color: olive;

    &:nth-child(2){
      color: purple;
    }
  }
}

→2つ目の要素、つまりItem2のみがpurpleとなる。

また、偶数のものを指定したい時はnth-child(2n), 奇数のものを表示したい時はnth-child(2n + 1)とすることでそれらを表示させることができる。

その他にも偶数を表す場合はnth-child(even),奇数を表す場合はnth-child(odd)とすることでもスタイルが割り振られる。

最後に

ここまで記事を読んでいただき、ありがとうございます。
本投稿が学習の一助となれば幸いです。

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
What you can do with signing up
1