CSS Attr Selectors
1 April 2025 | Category: CSS
CSS Attribute Selectors allow you to target HTML elements based on their attributes. Instead of using class or ID selectors, you can style elements directly based on their attributes.
🔹 1. Basic Attribute Selector ([attribute]
)
🔹 Selects elements that have a specific attribute, regardless of its value.
/* Selects all input elements that have the 'required' attribute */
input[required] {
border: 2px solid red;
}
✅ This applies a red border to all required input fields.
🔹 2. Attribute Equals Selector ([attribute="value"]
)
🔹 Selects elements where the attribute value exactly matches.
/* Selects all buttons with type="submit" */
button[type="submit"] {
background-color: green;
color: white;
}
✅ Styles only submit buttons, not other buttons.
🔹 3. Attribute Contains Selector ([attribute*="value"]
)
🔹 Selects elements whose attribute contains the given value anywhere.
/* Selects all links containing "google" in the href */
a[href*="google"] {
color: blue;
font-weight: bold;
}
✅ This targets links like:
<a href="https://www.google.com">Google</a>
<a href="https://google.co.in">Google India</a>
🔹 4. Attribute Starts With Selector ([attribute^="value"]
)
🔹 Selects elements whose attribute starts with the given value.
/* Selects all links that start with 'https' */
a[href^="https"] {
color: green;
text-decoration: underline;
}
✅ This ensures external secure links are styled differently.
🔹 5. Attribute Ends With Selector ([attribute$="value"]
)
🔹 Selects elements whose attribute ends with a specific value.
/* Selects all images ending with '.png' */
img[src$=".png"] {
border-radius: 10px;
}
✅ This applies styling only to PNG images.
🔹 6. Attribute With Space ([attribute~="value"]
)
🔹 Selects elements where the attribute contains a specific word separated by spaces.
/* Selects all elements where class contains 'featured' */
div[class~="featured"] {
background: yellow;
}
✅ This will match:
<div class="featured">Special Offer</div>
<div class="featured sale">Discount</div>
❌ Won’t match:
<div class="best-featured">No match</div>
🔹 7. Attribute With Hyphen ([attribute|="value"]
)
🔹 Selects elements where the attribute starts with the value, or is followed by a hyphen (-
).
/* Selects all elements with lang="en" or lang="en-US" */
p[lang|="en"] {
font-style: italic;
}
✅ This will match:
<p lang="en">English Text</p>
<p lang="en-US">American English</p>
❌ Won’t match:
<p lang="eng">Not selected</p>
📌 Conclusion
✔ CSS Attribute Selectors make it easy to style elements without classes or IDs.
✔ They work great for styling forms, links, and images dynamically.
✔ You can target elements based on partial matches (starts with, contains, ends with).