HTML サンプル
<ul> <li><a href="#top">TOP</a></li> <li><a href="https://developer.mozilla.org">mozilla</a></li> <li><a href="https://example.com">example</a></li> <li><a href="https://www.yahoo.co.jp">yahoo</a></li></ul>基本的な属性セレクタ
/* 前方一致: "#" から始まる */a[href^="#"] { color: fuchsia;}
/* 後方一致: ".org" で終わる */a[href$=".org"] { color: orange;}
/* 部分一致: "example" を含む */a[href*="example"] { color: red;}
/* 複合条件: "https" で始まり ".jp" で終わる */a[href^="https"][href$=".jp"] { color: green;}セレクタ一覧
| セレクタ | 意味 |
|---|---|
[attr] | 属性が存在する |
[attr="value"] | value と完全一致 |
[attr^="value"] | value で始まる |
[attr$="value"] | value で終わる |
[attr*="value"] | value を含む |
大文字・小文字を無視する(i フラグ)
末尾に i を付けると大文字小文字を区別しない。
/* ".pdf" でも ".PDF" でもマッチ */a[href$=".pdf" i]::after { content: " (PDF)";}:not() との組み合わせ
/* 外部リンク(http/https)のみ対象 */a[href^="http"]::after { content: " ↗";}
/* ページ内リンク(#)は除外 */a[href^="http"]:not([href*="example.com"])::after { content: " ↗";}実用例: ファイルタイプ別アイコン
/* PDF リンクにラベルを付ける */a[href$=".pdf" i]::after { content: " [PDF]"; font-size: 0.75em; color: #c00;}
/* 外部リンクに矢印アイコン */a[href^="https://"]:not([href^="https://example.com"])::after { content: " ↗";}
/* アンカーリンクはスタイルなし */a[href^="#"] { text-decoration: none;}詳細度
属性セレクタの詳細度はクラスセレクタと同じ (0, 1, 0)。
a[href^="#"] { } /* (0, 1, 0) — クラスと同等 */a.internal { } /* (0, 1, 1) — クラス + 要素でこちらが勝つ */
hsb.horse