classやidなどの属性が付いていないHTMLタグを、セレクターで選択したい時に使うのが、nth-of-typeです。
順番で選択する以外にも、何番毎という繰り返しの選択もできるし、○番以降や以前の様な選択もできます。
要するに、色々と柔軟な選択ができてしまうのが、"nth-of-type"という機能です。
ちなみに、解説ページでは、次のように書かれています。
:nth-of-type() CSS の擬似クラスで、兄弟要素のグループの中で指定された型 (タグ名) の要素を、位置に基づいて選択します。 参考 : https://developer.mozilla.org/ja/docs/Web/CSS/:nth-of-type実際に、サンプルを見て、できる事を理解して、実際に自分でcssを書いて使ってみましょう。
使い方サンプル
3番目の子要素を選択
1
2
3
4
5
.sample-1 > *:nth-of-type(3){
background-color:red;
}
リストのストライプ(1つおき[偶数]に背景色を変える)
| # | 日付 | 商品 | 金額 |
|---|---|---|---|
| 1 | 2023/5/1 | リンゴ | ¥100 |
| 2 | 2023/5/2 | みかん | ¥80 |
| 3 | 2023/5/3 | バナナ | ¥120 |
| 4 | 2023/5/4 | ぶどう | ¥400 |
| 5 | 2023/5/5 | イチゴ | ¥350 |
.sample-2 tbody tr:nth-of-type(2n){
background-color:#eee !important;
}
リストのストライプ(1つおき[奇数]に背景色を変える)
| # | 日付 | 商品 | 金額 |
|---|---|---|---|
| 1 | 2023/5/1 | リンゴ | ¥100 |
| 2 | 2023/5/2 | みかん | ¥80 |
| 3 | 2023/5/3 | バナナ | ¥120 |
| 4 | 2023/5/4 | ぶどう | ¥400 |
| 5 | 2023/5/5 | イチゴ | ¥350 |
.sample-3 tbody tr:nth-of-type(2n+1){
background-color:#eee !important;
}
:nth-child()との違い
:htn-of-typeと似ている機能に、:nth-child()というのがあります。 :nth-of-type()は、タグの分類に応じた順番で、 :nth-child()は、子要素全ての順番で対応します。 ハッキリ言って、:nth-child()は使う箇所が限られてしまうので、:nth-of-type()を使ったほうがミスが起きにくくなるでしょう。p-1
p-2
p-3
div-1div-2div-3
<div class='sample-4'>
<p>p-1</p>
<p>p-2</p>
<p>p-3</p>
<div>div-1</div>
<div>div-2</div>
<div>div-3</div>
</div>
.sample-4 *:nth-child(2){
background-color:red;
color:white;
}
.sample-4 *:nth-of-type(3){
background-color:blue;
color:white;
}
0 件のコメント:
コメントを投稿