CSS Attribute Selectors


🔹 What Are CSS Attribute Selectors?

CSS Attribute Selectors allow you to select elements based on the presence or value of an attribute. They are powerful for targeting elements without needing extra classes or IDs.


🔸 1. Basic Attribute Selector

input[type="text"] {
  border: 2px solid green;
}

Targets all <input> elements with type="text".


🔸 2. Attribute Exists Selector ([attr])

a[target] {
  color: red;
}

Targets all anchor (<a>) tags that have a target attribute.


🔸 3. Attribute Value Contains ([attr~="value"])

[title~="help"] {
  background-color: yellow;
}

Selects elements whose title contains the word "help" (whole word match).


🔸 4. Attribute Starts With ([attr^="value"])

a[href^="https"] {
  color: green;
}

Matches elements where attribute starts with "https".


🔸 5. Attribute Ends With ([attr$="value"])

img[src$=".png"] {
  border-radius: 10px;
}

Selects all images whose src ends with .png.


🔸 6. Attribute Contains ([attr*="value"])

a[href*="login"] {
  font-weight: bold;
}

Selects anchor tags with "login" anywhere in the href value.


🔸 7. Attribute Equals Multiple Words ([attr|="value"])

[lang|="en"] {
  font-style: italic;
}

Matches lang="en" or lang="en-US", etc.


Practice Questions

Q1. Style all input elements of type checkbox.

Q2. Select links that open in new tab (target="_blank").

Q3. Change color of all elements with a data-status attribute.

Q4. Target <img> elements with .jpg at the end.

Q5. Make all buttons with disabled attribute appear faded.

Q6. Apply bold style to links that contain “signup” in their href.

Q7. Add padding to all inputs with a placeholder.

Q8. Set a red border for inputs with type="password".

Q9. Italicize all elements where lang starts with en.

Q10. Add underline to links that start with "mailto:".


Go Back Top