AI Workshop: learn to build apps with AI →
CSS Selectors: How to Use CSS Attribute Selectors

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Attribute selectors let you select elements based on their attributes or attribute values.

Attribute Presence Selector

Check if an element has an attribute using the [] syntax:

p[id] {
  color: yellow;
}

This selects all p tags that have an id attribute, regardless of its value.

Exact Attribute Value

Use = to match an exact attribute value:

p[id="my-id"] {
  color: yellow;
}
input[type="text"] {
  border: 1px solid gray;
}

Partial Attribute Value Matching

Several operators let you match partial attribute values:

OperatorDescription
*=Contains the value anywhere
^=Starts with the value
$=Ends with the value
|=Equals or starts with value followed by hyphen
~=Contains value as a whole word (space-separated)

Examples

/* Contains "dog" anywhere */
[class*="dog"] {
  color: brown;
}

/* Starts with "btn" */
[class^="btn"] {
  cursor: pointer;
}

/* Ends with "-primary" */
[class$="-primary"] {
  background: blue;
}

/* Value is "en" or starts with "en-" (useful for lang attribute) */
[lang|="en"] {
  quotes: '"' '"';
}

/* Contains "featured" as a whole word */
[class~="featured"] {
  border: 2px solid gold;
}

Case Insensitivity

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

a[href$=".PDF" i] {
  color: red;
}

This matches .pdf, .PDF, .Pdf, etc.

Practical Examples

Style all external links:

a[href^="http"] {
  padding-right: 20px;
  background: url(external-icon.svg) right center no-repeat;
}

Style required form fields:

input[required] {
  border-left: 3px solid red;
}

Style specific input types:

input[type="email"],
input[type="tel"] {
  width: 100%;
}

Lessons in this unit:

0: Introduction
1: How to Use Basic CSS Selectors
2: ▶︎ How to Use CSS Attribute Selectors
3: How to Use CSS Pseudo-Classes
4: How to Use CSS Pseudo-Elements