Quiz Entry - updated: 2026.07.14
How do attribute selectors work in CSS?
Attribute selectors target elements by the presence or value of an HTML attribute, written in square brackets like [type="email"], so you can style elements that share an attribute rather than a class.
You can restrict a rule to elements that simply have an attribute, or whose attribute matches a value in various ways:
/* Every h1 that has an align attribute (any value) */
h1[align] { color: #123456; }
/* Paragraphs whose name attribute contains the substring "Text" */
p[name*="Text"] { font-variant: small-caps; }
/* Any element at all with align exactly "center" */
*[align=center] { color: #654321; }
The matching operators are worth knowing because they cover most real needs:
| Selector | Matches when the attribute... |
|---|---|
[attr] |
exists at all |
[attr=value] |
equals value exactly |
[attr~=value] |
contains value as one whole word in a space-separated list |
[attr^=value] |
starts with value |
[attr$=value] |
ends with value |
[attr*=value] |
contains value as a substring |
A genuinely useful pattern is flagging links by their target, for example colouring secure vs insecure links or appending an icon to PDFs:
a[href^="https"] { color: green; } /* starts with https */
a[href$=".pdf"] { font-weight: bold; } /* ends in .pdf */
Go deeper:
Attribute selectors (MDN) — full reference for every matching operator (
~=,^=,$=,*=,|=) plus the case-sensitivity flags.