Web制作で役立つメモをWEB MEMO LOG

2016.11.07

【CSS】n番目の要素を指定できる「nth-child」と「nth-of-type」の違いと方法

便利なn番目の要素を指定できる「nth-child」と「nth-of-type」ですが、違いや方法をメモメモ。

▼E:nth-child(n):親要素のn番目の子要素であるE要素

/*  最初の要素(親要素から見て、子要素すべての最初)*/
:first-child

/*  最後の要素(親要素から見て、子要素すべての最後)*/
:last-child

/* X番目 */
:nth-child(X)

/* 最後からX番目 */
:nth-last-child(X)

/* X番目以降 */
:nth-child(n+X)

/* X番目以前 */
:nth-child(-n+X)

/* 最後からX個 */
:nth-last-child(-n+X)

/* 最後からX番目以前 */
:nth-last-child(n+X)

▼E:nth-of-type(n):親要素内で兄弟関係にあるE要素でn番目のもの

/*  ある要素の最初(親要素から見て、ある子要素の最初)*/
:first-of-type

/*  ある要素の最後(親要素から見て、ある子要素の最後)*/
:last-of-type

/* X番目 */
:nth-of-type(X)

/* 最後からX番目 */
:nth-last-of-type(X)

/* X番目以降 */
:nth-of-type(n+X)

/* X番目以前 */
:nth-of-type(-n+X)

/* 最後からX個 */
:nth-last-of-type(-n+X)

/* 最後からX番目以前 */
:nth-last-of-type(n+X)

【参考】
何番目系の便利なCSSまとめ
CSS3セレクタ「nth-child」と「nth-of-type」の使い方と違い

About Site

同じことを何度も検索していたりするんで、検索して解決したことを残そうと思いまして。