0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CSS :nth-child()疑似クラス:n番目の子要素の選択

0
Posted at

😄この投稿は、codingeverybody.jpのコンテンツをもとに作成しています。

定義と使い方

:nth-child(n)は、親要素の子要素の中で順序がn番目にあたる要素を選択する疑似クラスです。
例えば、:nth-child(2)は、子要素の中で2番目に位置する要素を選択します。

基本例

--- HTML ---
<ol>
    <li>li</li>
    <li>li</li>
    <li>li</li>
    <li>li</li>
    <li>li</li>
</ol>

--- CSS ---
ol > :nth-child(2) { /* <ol>の子要素の中で2番目に位置する要素を選択 */
    background-color: yellow;
}

構文

/* 正の整数:n番目 */
:nth-child(1) /* 任意の子要素の中から1番目の要素を選択 */
li:nth-child(1) /* 任意の子要素の中から1番目にあたる<li>要素を選択 */

/* 正の整数:n番目 */
:nth-child(7) /* 任意の子要素の中から7番目の要素を選択 */
li:nth-child(7) /* 任意の子要素の中から7番目にあたる<li>要素を選択 */

/* キーワード:even / odd */
:nth-child(odd) /* 任意の子要素の中から奇数(1,3,5,...)番目の要素を選択 */
li:nth-child(even) /* 任意の子要素の中から偶数(2,4,6,...)番目にあたる<li>要素を選択 */

/* 数式:An+B */
:nth-child(2n) /* 任意の子要素の中から2の倍数番目の要素を選択 */
li:nth-child(2n) /* 任意の子要素の中から2の倍数番目にあたる<li>要素を選択 */

:nth-child(3n) /* 任意の子要素の中から3の倍数番目の要素を選択 */
li:nth-child(3n) /* 任意の子要素の中から3の倍数番目にあたる<li>要素を選択 */

:nth-child(3n+1) /* 任意の子要素の中から3の倍数に1を加えた番目の要素を選択 */
:nth-child(3n-1) /* 任意の子要素の中から3の倍数から1を引いた番目の要素を選択 */

形式構文

:nth-child(index | odd | even | an+b) {
    /* ... */
}

引数nの値

1. 非負の整数インデックス値

親要素の子要素に非負の整数でインデックスを付け、その順序に該当する要素を選択します。インデックスは1から始まります。

li:nth-child(2) { /* 非負の整数を指定可能 */
    border: 3px solid blue;
}

2. キーワード値[odd(奇数番目)またはeven(偶数番目)]

odd : 親要素の子要素の中から奇数番目(1,3,5,7,...)に位置する要素を選択します。
even : 親要素の子要素の中から偶数番目(2,4,6,8,...)に位置する要素を選択します。

li:nth-child(even) {
    background-color: yellowgreen;
}

3. An+B形式のユーザー定義パターン

An+B形式のユーザー定義パターンを満たすインデックスを持つ要素を選択します。

  • Aは整数インデックスの増減ステップを示します。
  • Bは整数のオフセットを表し、省略可能です。
  • nは0から始まるすべての正の整数を表します。
:nth-child(5n)
/*
 * 0[=5×0]、5[=5×1]、10[=5×2]、15[=5×3]、...番目の要素を表します。
 * 要素のインデックスは1から始まるため、0番目の要素は存在せず、結果として5、10、15、...番目の要素を表します。
 * 結論として、5nは5の倍数番目の要素を選択します。
*/

:nth-child(5n-1)
/*
 * -1[=5×0-1]、4[=5×1-1]、9[=5×2-1]、14[=5×3-1]、...番目の要素を表します。
 * 要素のインデックスは1から始まるため、-1番目の要素は存在せず、結果として4、9、14、...番目の要素を表します。
 * 結論として、5n-1は5の倍数番目の1つ前にあたる要素を選択します。
*/

:nth-child(5n+1)
/*
 * 1[=5×0+1]、6[=5×1+1]、11[=5×2+1]、16[=5×3+1]、...番目の要素を表します。
 * 1、6、11、16、...番目の要素を表します。
 * 結論として、5n+1は5の倍数番目の1つ後にあたる要素を選択します。
*/

:nth-child(n)
/*
 * 0[0]、1[1]、2[2]、3[3]、...番目の要素を表します。
 * 要素のインデックスは1から始まるため、0番目の要素は存在せず、結果として1、2、3、...番目の要素を表します。
 * 結論として、nはすべての要素を表します。
*/

参考資料

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?