LoginSignup
0
0

More than 3 years have passed since last update.

n番目のスタイルを変えたい時に便利な疑似クラスnth-child

Last updated at Posted at 2020-02-26

nth-childとは

ある要素の隣接している子要素を最初から数えて、n番目にあたる要素にスタイルを当てることができる!

擬似クラス :nth-child()の使い方まとめ

nth-child(n)  n番目
nth-child(3n)  3の倍数
nth-child(3n-1)  3の倍数-1番目に適用
nth-child(n-4)  4番目以降に適用
nth-child(even),  :nth-child(2n)  偶数
nth-child(odd), :nth-child(2n-1)  奇数

n番目

:nth-child(n)

例えば、3の倍数の場合 :nth-child(3) になります。
以下の記述で3の倍数のリストの文字色だけ赤色に変えることができます。

sample.css
li:nth-child(3n) {
  color: red;
  font-weight: bold;
}

3の倍数-1番目に適応

:nth-child(3n-1)

sample.css
li:nth-child(3n-1) {
  color: red;
  font-weight: bold;
}

例えば3つ横並びにしたとき、真ん中のみスタイルを適用したい時に便利!
スクリーンショット 2020-02-13 17.22.58.png


nth-child(n)を使えばhamlのクラス名を変えて都度scssを書く必要がないので便利ですね!!!

0
0
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
0
0