Attribute Selector chọn element dựa trên **attribute** và **giá trị** của nó.
Các loại Attribute Selector
| Pattern | Tên | Mô tả | Ví dụ |
|---|---|---|---|
[attr] | Presence | Có attribute (bất kỳ giá trị) | p[lang] |
[attr="val"] | Exact match | Giá trị chính xác "val" | p[lang="fr"] |
[attr~="val"] | Word match | Giá trị chứa từ "val" (space-separated) | p[lang~="fr"] |
[attr|="val"] | Prefix match | Giá trị là "val" hoặc bắt đầu "val-" | p[lang|="en"] (en, en-US, en-GB) |
[attr^="val"] | Starts with | Giá trị bắt đầu bằng "val" | a[href^="https"] |
[attr$="val"] | Ends with | Giá trị kết thúc bằng "val" | a[href$=".pdf"] |
[attr*="val"] | Contains | Giá trị chứa "val" ở bất kỳ đâu | img[src*="logo"] |
[attr="val" i] | Case-insensitive | Không phân biệt hoa/thường (CSS4) | a[href$=".PDF" i] |
[attr="val" s] | Case-sensitive | Phân biệt hoa/thường (CSS4) | a[href$=".pdf" s] |
Ví dụ thực tế
/* Input text, email, password, search... */
input[type="text"],
input[type="email"],
input[type="password"] {
border: 1px solid #ccc;
}
/* Link ngoài (target=_blank) */
a[target="_blank"]::after {
content: " ↗";
}
/* File PDF */
a[href$=".pdf"]::before {
content: "📄 ";
}
/* HTTPS links */
a[href^="https://"] {
color: green;
}
Độ đặc hiệu
Attribute selector: (0, 0, 1, 0) = 10 (ngang class, pseudo-class). Cao hơn type selector (1).