CSS Attribute Selectors
CSS attribute selectors enable targeting HTML elements by their attributes and values, offering a robust method for selective styling that enhances the flexibility and accuracy of your CSS.
Introduction
CSS attribute selectors offer a powerful way to target HTML elements based on their attributes and attribute values. This enables you to apply styles selectively, enhancing the specificity and flexibility of your CSS. Attribute selectors can match elements based on whether an attribute contains, starts with, ends with, is present, or is not equal to a certain value.
Types of Attribute Selectors
Attribute selectors in CSS allow you to target elements based on their attributes and values. The main types include selectors that check if an attribute contains, starts with, ends with a specific value, is present, or is not equal to a specified value.
Contains
[attribute*=value]
- Selects elements where the attribute's value contains the specified value.
img[src*="jpg"] { display: block; }
Starts With
[attribute^=value]
- Selects elements where the attribute's value starts with the specified value.
input[type^="text"] { width: 200px; }
Ends With
[attribute$=value]
- Selects elements where the attribute's value ends with the specified value.
a[href$=".pdf"] { font-weight: bold; }
Attribute Presence
[attribute]
- Selects elements that have the specified attribute, regardless of its value.
img[alt] { border: 1px solid #ccc; }
Attribute Not Equal To
[attribute!=value]
- Selects elements where the attribute's value is not equal to the specified value.
input[type!=password] { border: 1px solid green; }
Do You Know?
You can combine attribute selectors with other CSS selectors for more specific targeting.
Avoid This!
Avoid using attribute selectors that rely on specific values that may change in the future. Instead, use more generic selectors.
Important Note
Attribute selectors are case-insensitive in HTML, so [href="example.com"]
is the same as [Href="example.com"]
.
Summary
CSS attribute selectors allow you to target elements based on attributes and values.
Common selectors include exact match, contains, starts with, ends with, attribute presence, and not equal to.
Use them for targeted styling and enhancing your CSS flexibility.