提示属性选择器不参与 DOM 结构判断,只看属性值,因此性能开销与类选择器基本相当,可以放心在大型项目中使用。
Chapter 2 · Section 2.3
Attribute Selectors
Attribute selectors match elements by their HTML attributes and values, without requiring extra class names — especially handy for forms, links, and multilingual scenarios.
/* auto-add an icon to external links */a[href^="http"]::after {
content: " ↗";
}
/* mark PDF links in red */a[href$=".pdf"] {
color: #b3452c;
}
Case Sensitivity
By default, attribute value matching is case-sensitive (except for HTML attribute names themselves). Adding i at the end of the selector ignores case, while adding s forces case sensitivity.
TipAttribute selectors do not look at the DOM structure, only attribute values, so their performance cost is about the same as class selectors — feel free to use them in large projects.