Attribute Selectors

Match elements by their attributes and attribute values.

Syntaxinput[type="text"] { }

Attribute selectors match elements based on their attributes, written in square brackets.

  • [type] — has the attribute.
  • [type="text"] — exact value.
  • [href^="https"] — value starts with.
  • [src$=".png"] — value ends with.
  • [class*="btn"] — value contains.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer styles all external links differently by selecting a[href^='https://'] and adding an external-link icon via CSS.
  • A designer targets input[type='text'] and input[type='email'] separately to give each a distinct border color in a form.
  • A developer uses [data-theme='dark'] on the root element to apply an entire dark-mode color palette without JavaScript class toggling.

More examples

Exact attribute value match

Targets only text inputs using [attr=value], keeping other input types unaffected.

Example · css
input[type="text"] {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px;
  width: 100%;
}

Attribute starts-with for external links

Uses ^= to match any href that starts with 'https', visually marking all external links with an icon.

Example · css
a[href^="https"] {
  padding-right: 16px;
  background: url('external-icon.svg') no-repeat right center;
  background-size: 12px;
}

Attribute contains for file types

Uses $= to match hrefs ending in specific extensions and appends a text label after PDF and ZIP links.

Example · css
a[href$=".pdf"]::after {
  content: " (PDF)";
  font-size: 0.8em;
  color: #c0392b;
}
a[href$=".zip"]::after {
  content: " (ZIP)";
  color: #7f8c8d;
}

Discussion

  • Be the first to comment on this lesson.
Attribute Selectors — CSS | SoundsCode