CSS Attribute Selector ([attr]) — Selecting by Element Attributes

Learn all CSS attribute selector variations: [attr], [attr=value], [attr~=value], [attr|=value], [attr^=value], [attr$=value], and [attr*=value] with practical examples.

Attribute Selectors

Detailed Explanation

CSS Attribute Selectors

Attribute selectors target elements based on the presence or value of HTML attributes. They are incredibly versatile and come in seven variations.

All Variations

Selector Matches
[attr] Has the attribute (any value)
[attr="value"] Exact match
[attr~="value"] Contains word (space-separated list)
`[attr ="value"]`
[attr^="value"] Starts with value
[attr$="value"] Ends with value
[attr*="value"] Contains value anywhere

Examples

/* Any element with a title attribute */
[title] { cursor: help; }

/* Links to external sites */
a[href^="https://"] { }

/* Links to PDF files */
a[href$=".pdf"]::after { content: " (PDF)"; }

/* Data attributes */
[data-theme="dark"] { background: #000; }

/* Case-insensitive matching */
a[href$=".PDF" i] { } /* the 'i' flag */

Specificity

Every attribute selector has a specificity of (0, 1, 0) — the same as a class selector. This makes them interchangeable with classes in specificity calculations.

Case Sensitivity

By default, attribute values are case-sensitive. Add the i flag before the closing bracket for case-insensitive matching:

[type="submit" i] { }

Common Patterns

/* Style required form fields */
input[required] { border-left: 3px solid red; }

/* External links get an icon */
a[target="_blank"]::after { content: " ↗"; }

/* Language-specific styles */
[lang|="en"] { quotes: "“" "”"; }

Use Case

Attribute selectors are essential for styling form elements by type (input[type='email']), targeting data attributes in JavaScript frameworks ([data-state='active']), styling external links differently (a[href^='https']), indicating file types for download links (a[href$='.pdf']), and implementing internationalization styles based on the lang attribute.

Try It — CSS Selector Tester

Open full tool