今回はn番目系の擬似クラスの中で、対象の要素が隣接している必要があるものについてまとめていきます。
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
</ul>
対象の要素が隣接している必要がある擬似クラス
:first-child
ある要素内で最初の子要素を指定
li:first-child {
color: #ff6e9b;
font-weight: bold;
}
:last-child
ある要素内で最後の子要素を指定
li:last-child {
color: #ff6e9b;
font-weight: bold;
}
:nth-child(n)
先頭からn番目の子要素を指定する
nth-child(odd) : 奇数番目を指定
li:nth-child(odd) { color: #1b95e0; font-weight: bold; }
:nth-child(even) : 偶数番目を指定
li:nth-child(even) { color: #1b95e0; font-weight: bold; }
:nth-child(数式) :
nth-child(2) : 2番目の子要素を指定
li:nth-child(2) { color: #1b95e0; font-weight: bold; }
:nth-child(2n) : 2の倍数の子要素を指定
li:nth-child(2n) { color: #1b95e0; font-weight: bold; }
:nth-child(2n+1) : 1番目の子要素を指定し、その後2つおきに指定
li:nth-child(2n+1) { color: #1b95e0; font-weight: bold; }
:nth-child(2n+5) : 5番目の子要素を指定し、その後2つおきに指定
li:nth-child(2n+5) { color: #1b95e0; font-weight: bold; }
:nth-child(n+3) : 3番目以降の子要素を指定
li:nth-child(n+3) { color: #1b95e0; font-weight: bold; }
:nth-child(-n+3) : 3番目までの子要素を指定
li:nth-child(-n+3) { color: #1b95e0; font-weight: bold; }
:nth-child(n+3):nth-child(-n+7) : 3~7番目を指定
li:nth-child(n+3):nth-child(-n+7) { color: #1b95e0; font-weight: bold; }
:nth-last-child(n)
後ろから数えて、n番目の子要素を指定
nth-childと同様に、nの部分にはodd、even、n+1などの数式を指定できる。
:nth-last-child(odd) : 奇数番目の子要素を指定
li:nth-last-child(odd) { color: #ff6e9b; font-weight: bold; }
:nth-last-child(even) : 偶数番目の子要素を指定
li:nth-last-child(even) { color: #ff6e9b; font-weight: bold; }
:nth-last-child(3) : 3番目の子要素を指定
li:nth-last-child(3) { color: #ff6e9b; font-weight: bold; }
:nth-last-child(3n) : 3の倍数の子要素を指定
li:nth-last-child(3n) { color: #ff6e9b; font-weight: bold; }
:nth-last-child(3n+1) : 1番目の子要素を指定し、その後3つおきに指定
li:nth-last-child(3n+1) { color: #ff6e9b; font-weight: bold; }
:nth-last-child(n+4) : 4番目以降の子要素を指定
li:nth-last-child(n+4) { color: #ff6e9b; font-weight: bold; }
:nth-last-child(-n+4) : 4番目までの子要素を指定
li:nth-last-child(-n+4) { color: #ff6e9b; font-weight: bold; }
:only-child
ある要素内で子要素が唯一の場合に適用
<div class="item">
<h1>サンプル</h1>
<p>テキスト</p>
</div>
<div class="item">
<p>テキスト</p>
</div>
<div class="item">
<p>テキスト</p>
<p>テキスト</p>
</div>
.item p:only-child {
color: #e1a261;
font-weight: bold;
}