🔍 CSS Attribute Selectors

Last Updated: November 2025


Attribute selectors in CSS allow you to target HTML elements based on their attributes or attribute values.

They are especially useful when classes or IDs are not available, but you still want precise control.

🗣 Hinglish Tip: Jab tumhe unhi elements ko style karna ho jinke paas koi specific attribute ho — jaise required, type="email" ya target="_blank" — tab attribute selectors perfect kaam aate hain 😎


✏️ Basic Syntax

selector[attribute] {
  property: value;
}

Types of Attribute Selectors

SelectorDescriptionExample
[attr]Selects elements that have the attributeinput[required]
[attr="value"]Selects elements whose attribute value matches exactlya[target="_blank"]
[attr~="value"]Selects elements where attribute contains the word (space-separated)[class~="active"]
[attr|="value"]Matches value exactly OR starting with value-[lang|="en"]
[attr^="value"]Attribute value starts with given stringa[href^="https"]
[attr$="value"]Attribute value ends with given stringimg[src$=".png"]
[attr*="value"]Attribute contains the given substringa[href*="login"]

Attribute Presence

<input type="text" required /> <input type="email" />
input[required] {
  border: 2px solid red;
}

Exact Match

<a href="https://example.com" target="_blank">External Link</a>
a[target="_blank"] {
  color: blue;
}

Starts With (^=)

<a href="https://example.com">Internal Link</a>
a[href^="https"] {
  color: green;
}

Ends With ($=)

<img src="https://example.com/image.jpg" />
img[src$=".jpg"] {
  border-radius: 50%;
}

Contains (*=)

<a href="/user/profile">Profile</a> <a href="/user/settings">Settings</a>
a[href*="profile"] {
  color: red;
}

Multiple Attribute Selectors

<a href="https://example.com" target="_blank">External Link</a>
a[target="_blank"][href^="https"] {
  color: green;
}