Codectionary / Developer documentation / CSS

Attribute Selectors

Attribute selectors target elements based on the presence or value of an HTML attribute, using square bracket syntax. They support several matching modes beyond exact equality, including starts-with, ends-with, and contains, making them powerful for targeting elements without needing extra classes.

Syntax

[attr] { }
[attr="value"] { }
[attr^="value"] { }

Examples

Presence and Exact Match

Selecting by whether an attribute exists, or matches exactly.

[disabled] { opacity: 0.5; }              /* any element with a disabled attribute at all */
[type="submit"] { font-weight: bold; }     /* inputs with type exactly "submit" */
[target="_blank"] { }                      /* links that open in a new tab */

Pattern-Matching Attribute Values

Starts-with, ends-with, and contains matching.

a[href^="https://"] { }   /* href starts with https:// */
a[href$=".pdf"] { }        /* href ends with .pdf - useful for styling download links */
[class*="btn-"] { }        /* class contains "btn-" anywhere within it */

Parameters and values

  • [attr] (presence): Matches if the attribute exists, regardless of value
  • [attr="val"] (exact match): Matches only an exact value
  • [attr^="val"] (starts with): Matches values beginning with the given string
  • [attr$="val"] (ends with): Matches values ending with the given string
  • [attr*="val"] (contains): Matches values containing the given string anywhere

Best practices

  • Use [href$=".pdf"] style selectors to automatically style download links or external links without needing to add classes manually
  • Use [disabled] or [aria-expanded="true"] to style based on state attributes, keeping styling in sync with actual element state
  • Attribute selectors carry the same specificity as a class selector, so they combine predictably with other class-based rules
  • Prefer classes for styling hooks that are purely presentational, and reserve attribute selectors for cases tied to genuine HTML semantics or state

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation