
目次
CSSの:nth-child(n)は使い方を間違いやすい
CSSの:nth-child() は兄弟要素のグループの中での位置に基づいて選択します。
これを「要素:nth-child(n番目)」と要素のn番目を選択だと間違えるケースが多くあります。
例えば、以下のコードは「Paragraph 2」を「p:nth-child(2)」で指定して青色にしていますが、「Paragraph 3」を青くするにはどうすれば良いでしょうか?
See the Pen CSS :nth-child sample 1 by iwbjp (@xzdrtugn-the-reactor) on CodePen.
CSSのコーディング経験の浅い初心者だと大半は「p:nth-child(3)」と答えますが、これでは「Paragraph 3」は青くなりません。
See the Pen CSS :nth-child sample 2 by iwbjp (@xzdrtugn-the-reactor) on CodePen.
正解は「p:nth-child(4)」または「p:nth-of-type(3)」になります。
:nth-of-type(n)も使い方を間違いやすい
それなら:nth-of-type(n)を常に使えば良いのではと考える方もいるかもしれませんが、以下のようにCSSのclass名がタグに付いて、「.blue:nth-of-type(2)」のように指定しても、.blueの2番目は青色になりません。
See the Pen CSS :nth-child sample 3 by iwbjp (@xzdrtugn-the-reactor) on CodePen.
:nth-child(n of selector)を使う
前述のケースの場合は:nth-child(n of selector)を使うことで、2番目の.blueを指定できます。
:nth-child(2 of .blue) {
color: blue;
}
See the Pen CSS :nth-child sample 4 by iwbjp (@xzdrtugn-the-reactor) on CodePen.
テーブルの表などで:nth-child(even)を使って背景色を偶数の要素にだけ適用したいことがありますが、hidden属性で非表示にされると、背景色が交互に表示されないです。
See the Pen CSS :nth-child sample 5 by iwbjp (@xzdrtugn-the-reactor) on CodePen.
このようなケースの場合は:nth-child(even of :not([hidden]))を使います。
See the Pen CSS :nth-child sample 6 by iwbjp (@xzdrtugn-the-reactor) on CodePen.
display: noneで非表示になっている場合はstyle属性で指定します。
See the Pen CSS :nth-child sample 7 by iwbjp (@xzdrtugn-the-reactor) on CodePen.
:nth-child(n of selector) は全ブラウザ対応
:nth-child(n of selector)はあまり聞き慣れないし、この書き方を使用いるWebサイトが少ないです。
そのため、一部のブラウザにしか対応されていないのではないかと誤解されることがたまにありますが、:nth-child(n of selector)は全モダンブラウザに対応されています。
