CSS - Attribute Selectors

Overview

Estimated time: 10 minutes

Attribute selectors are perfect for targeting links, inputs, and components by their attributes and values.

Learning Objectives

  • Use exact, prefix, suffix, substring, word, and language attribute selectors.

Details & Examples

  • [attr], [attr="value"]
  • [attr^="prefix"], [attr$="suffix"], [attr*="substr"]
  • [attr~="word"], [attr|="lang"]

Pitfalls

  • Be precise with performance: [attr*=substr] can be slower than exact matches.

Checks for Understanding

  1. Which selector matches lang="en-US" and lang="en"?
Show answers
  1. [lang|="en"].

Exercises

  1. Style external links differently using attribute selectors.
  2. Target PDF links to add a small icon using ::after.
Suggested answers
  1. a[href^="http"]{ color: seagreen; }
  2. a[href$=".pdf"]::after{ content:"📄"; margin-left:.25em; }