LoginSignup
123
130

More than 3 years have passed since last update.

本当に使えるnth-childまとめ

Last updated at Posted at 2018-05-17

180520 追記 一部間違った記述があったので修正しました

はじめに

数学に弱いコーダーはnが入って来ると計算がわからなくなります。

だったら最初から覚えずによく使うものはメモするといいです。

特にX〜Yまで、という指定はよく使うと思います。
なるべく指定は短く書きたいですね。

基本

X番目

全ての基本です。

style.css
li:nth-child(X) {

}

最初のみ

first-childもありますが、記述スピードは(1)は、
同じくらいだと思います。編集性を考えてこちらの記述がいいと思います。

style.css
li:nth-child(1) {

}

最後のみ

last-childは数が変わっても常に最後を指定し続けます。
便利です。使いましょう。

style.css
li:last-child {

}

X~Y

X番目以前(最初からX番目まで)

style.css
li:nth-child(-n+X) {

}

X番目以降(X番目から最後まで)

style.css
li:nth-child(n+X) {

}

X番目からY番目まで

これが使えると、グッと記述が減らせます。
修正も楽ですよ。

style.css
li:nth-child(n+X):nth-child(-n+Y) {

}

X番目以外全部

notが絡むとよくわからなくなるのは私だけでしょうか。

style.css
li:not(:nth-child(X)) { 

}

偶数奇数

偶数番目

nth-child(even)もありますが、そもそも(2n)の方が
早く書けるので使わなくていいです。

style.css
li:nth-child(2n) {

}

奇数番目

nth=child(odd)(2n-1)、文字数はoddが少なくなりますが、後から変わった時の編集性を考えると2n-1がいいと思います。(たぶん)。
使い慣れれば、一目で奇数だな、とわかります。

style.css
li:nth-child(2n-1) {

}

ある条件の時、X番目からY番目を指定する

この辺を使えるようになると、記述をすごく減らせます。

X番目からY番目までの偶数ごとに

これも一行です。

style.css
li:nth-child(2n)li:nth-child(n+X):nth-child(-n+Y) {

}

X個以上の時、全てを選択

style.css
li:nth-last-child(n+X),
li:nth-last-child(n+X) ~ li {

}

X個以下の時、全てを選択

style.css
li:nth-last-child(-n+X):first-child, 
li:nth-last-child(-n+X):first-child ~ li {
}
123
130
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
123
130