CSSで特定の順番や種類の要素を指定してスタイルを調整する

CSSで特定の順番 画像1

CSSは、擬似クラスを使ってスタイル付与の条件を細かく設定できる。「最初だけボーダーを付けない」や「背景色をストライプにする」などが代表例。

上手く使いこなせると、「HTML構造は今更変えられないのでCSSの追加で何とかできないか」といったクイズのような古いサイト改修案件も捌きやすくなる。

擬似クラスの特徴

擬似クラスは基本的に「親要素からみて何番目の子要素」というルールで対象を特定する。また、大きく ●●-child ●●-of-type という2つの書き方があり、●●-of-type で書くと同じ種類だけを数えるようにできる。

また、複数組み合わせることも可能。その分詳細度が高まってしまう点には注意。

最初・最後

/* 最初の要素 */
:first-child {
  color: red;
}

/* 最後の要素 */
:last-child {
  color: red;
}

/* 同じ種類で順番が最初の要素 */
:first-of-type {
  color: red;
}

/* 同じ種類で順番が最後の要素 */
:last-of-type {
  color: red;
}

偶数・奇数

/* 順番が奇数の要素 */
:nth-child(odd) {
  color: red;
}

/* 順番が偶数の要素 */
:nth-child(even) {
  color: red;
}

/* 同じ種類で順番が奇数の要素 */
:nth-of-type(odd) {
  color: red;
}

/* 同じ種類で順番が偶数の要素 */
:nth-of-type(even) {
  color: red;
}

特定の順番

/* 順番が2番目の要素 */
:nth-child(2) {
  color: red;
}

/* 同じ種類で順番が2番目の要素 */
:nth-of-type(2) {
  color: red;
}

特定の倍数

/* 順番が3の倍数の要素 */
:nth-child(3n) {
  color: red;
}

/* 同じ種類で順番が3の倍数の要素 */
:nth-of-type(3n) {
  color: red;
}

特定の範囲

/* 順番が5番目までの要素 */
:nth-child(-n+5) {
  color: red;
}

/* 順番が6番目以降の要素 */
:nth-child(n+6) {
  color: red;
}

/* 同じ種類で順番が5番目までの要素 */
:nth-of-type(-n+5) {
  color: red;
}

/* 同じ種類で順番が6番目以降の要素 */
:nth-of-type(n+6) {
  color: red;
}

後ろから数える

:nth-child():nth-last-child() に、:nth-of-type():nth-last-of-type() へ置き換えることによって、後ろから数えて指定できる。

応用例

/* 6〜8番目のliの文字色を赤くする */
li:nth-child(n+6):nth-child(-n+8) {
  color: red;
}

/* 2の倍数で4の倍数でないliに右線を付ける */
li:nth-child(2n):not(:nth-child(4n)) {
  border-right: 1px solid black;
}

/* セクション直下の要素を各1em離す */
section > *:not(:first-child) {
  margin-top: 1em;
}