【CSS】セレクターまとめ
:first-childと:first-of-typeの違い
- first-child:親要素から見た一つ目の要素を選択
- first-of-type:親要素から見た指定されたタグの一つ目の要素を選択
<article>
<h1>tiltle</h1>
<p>テキスト1</p>
<p>テキスト2</p>
<p>テキスト3</p>
</article>
/* article内の一つ目の要素がh1のためスタイルは当たらない */
article p:first-child {
color: red;
}
/* 1番目のpが指定される */
article p:first-of-type {
color: red;
}
- 逆に後ろから一つ目を選択したい場合は
:last-child
,:last-of-type
/* 3番目のpが指定される */
article last-child {
color: red;
}
/* 3番目のpが指定される */
article p:last-of-type {
color: red;
}
- 任意の順番の要素を選択したい場合は
:nth-child
,:nth-of-type
/* 1番目のpが指定される */
article nth-child(2) {
color: red;
}
/* 2番目のpが指定される */
article p:nth-of-type(2) {
color: red;
}
:not
- 指定したセレクタ以外の要素を選択
/* 1番目のp以外が指定される */
article p:not(first-of-type) {
color: red;
}
擬似要素 ::before, ::after
- ::before:指定した要素の後に任意の値やプロパティを付与する
p:first-of-type::before {
content: '!!!';
}
<article>
<h1>tiltle</h1>
<p>テキスト1!!!</p>
<p>テキスト2</p>
<p>テキスト3</p>
</article>
- ::after:指定した要素の前に任意の値やプロパティを付与する
p:first-of-type::after {
content: '!!!';
}
<article>
<h1>tiltle</h1>
<p>!!!テキスト1</p>
<p>テキスト2</p>
<p>テキスト3</p>
</article>
部分文字列一致
/* 完全一致 */
input[value="hoge"] {
// css
}
/* 部分一致 */
input[value*="hoge"] {
// css
}
/* 前方一致 */
input[value^="hoge"] {
// css
}
/* 後方一致 */
input[value$="hoge"] {
// css
}
子孫結合子
- 孫要素を選択
main article h1 {
font-size: 3rem;
}
子結合子
- 直下の子要素のみを選択
main > h1 {
font-size: 3rem;
}
隣接兄弟結合子
- 2番目以降のpタグにマージンを設定したい場合
article p:not(:first-of-type) {
margin: 2rem;
}
- 上記と同意。article配下の1番目のp以降を選択
article p + p {
margin: 2rem;
}
一般兄弟結合子
- h1よりも後ろにあるpを選択
article h1 ~ p {
color: red;
}
参考
基礎からちゃんと学ぶ CSS 入門!この講座だけでセレクターは完結できます!【ヤフー出身エンジニアが教える初心者向けプログラミング講座】
MDN:属性セレクター