css 最初の要素、最後の要素だけ(疑似要素: first-of-type, first-child, last-of-type, last-child)
最初の要素だけCSSをあてたい
作成日:2022-10-03, 更新日:2023-01-31
最初(or 最後)に現れる子要素(first-child, last-child)
親要素から指定しておかないと余計なトコで影響がでるかもしれないので注意が必要
サンプルとソース
「親要素: #wrp_hasChild1」の中の「最初(or 最後)の子要素」が「pタグ」だったら何かする
<style> #wrp_hasChild1 p:first-child{ color: red; } #wrp_hasChild1 p:last-child{ color: blue; } </style> <div id="wrp_hasChild1"> <p>あめんぼ</p> <p>赤いな</p> <p>あいうえお</p> </div>
あめんぼ
赤いな
あいうえお
指定したタグが最初(or 最後)に現れる子要素→「子要素:指定タグ」の最初(or 最後)(first-child, last-child)
サンプルとソース
<style> #wrp_hasChild2 p:first-of-type{ color: red; } #wrp_hasChild2 p:last-of-type{ color: blue; } </style> <div id="wrp_hasChild2"> <div>學問のうた「五十音」 / 北原 白秋</div> <p>柿の木</p> <p>栗の木</p> <p>かきくけこ</p> <div>白秋童謡集 第五集『祭の笛』</div> </div>
學問のうた「五十音」 / 北原 白秋
柿の木
栗の木
かきくけこ
白秋童謡集 第五集『祭の笛』
まとめ: チートシート
- 最初(or 最後)に現れる子要素: first-child, last-child
- 指定したタグが最初(or 最後)に現れる子要素: first-of-type, last-of-type
→「子要素:指定タグ」の最初(or 最後)
<div id="wrp_hasChild0"><!-- ▼ 子要素 --> <div>鳥精</div> <span>セセリ</span> <p>豚精</p> <span>ナンコツ</span> <p>丸ごとシマウマ</p> <!-- 子要素 ▲ --></div>
対象 | 概要 | 指定例 | メモ |
---|---|---|---|
<div>鳥精</div> | 最初に現れる子要素 | #wrp_hasChild0 div:first-child{} ▼タグを指定なくてもOK #wrp_hasChild0 *:first-child{} |
|
指定したタグが最初に現れる子要素→「子要素:指定タグ」の最初 | #wrp_hasChild0 div:first-of-type{} | 「指定したタグ」が対象になるのであって「指定したクラス」は使えない | |
指定したタグが最後に現れる子要素→「子要素:指定タグ」の最後 | #wrp_hasChild0 div:last-of-type{} | 「指定したタグ」が対象になるのであって「指定したクラス」は使えない | |
<span>セセリ</span> | 指定したタグが最初に現れる子要素→「子要素:指定タグ」の最初 | #wrp_hasChild0 span:first-of-type{} | 「指定したタグ」が対象になるのであって「指定したクラス」は使えない |
<p>豚精</p> | 指定したタグが最初に現れる子要素→「子要素:指定タグ」の最初 | #wrp_hasChild0 p:first-of-type{} | 「指定したタグ」が対象になるのであって「指定したクラス」は使えない |
<span>ナンコツ</span> | 指定したタグが最後に現れる子要素→「子要素:指定タグ」の最後 | #wrp_hasChild0 span:last-of-type{} | 「指定したタグ」が対象になるのであって「指定したクラス」は使えない |
<p>丸ごとシマウマ</p> | 最後に現れる子要素 | #wrp_hasChild0 p:last-child{} ▼タグを指定なくてもOK #wrp_hasChild0 *:last-child{} |
|
指定したタグが最後に現れる子要素→「子要素:指定タグ」の最後 | #wrp_hasChild0 p:last-of-type{} | 「指定したタグ」が対象になるのであって「指定したクラス」は使えない |
親要素を指定しない場合
下記のように親要素がなく、指定したタグに疑似要素の「first-child」を指定した場合
p:first-child { color: red; }
この場合、親要素を持つpタグで、そのpタグが親要素の最初に現れる子要素である場合・・・となる
→「pタグは親要素を持っている」と「子要素の一番目がpタグである」の条件を満たせば適用される
<style> p:first-child{ color: red; } </style> <body> <p>aaa</p> <div> <p>aaa</p> <p>bbb</p> <p>ccc</p> <div> <p>aaa</p> <p>bbb</p> </div> </div> </body>
これだと「<p>aaa</p>」がすべて「親要素を持つpタグで、そのpタグが親要素の最初に現れる子要素」という条件を満たすので「color: red;」が適用される