Attribute Selectors
Attribute Selectors
CSS attribute selectors allow you to style HTML elements based on their attributes and attribute
values. They are highly useful for targeting elements dynamically and enhancing flexibility in
design. Here's a detailed breakdown of CSS attribute selectors, their types, and real-time use
cases.
Matches elements that have the specified attribute, regardless of the value.
Example:
a[href] {
color: blue; /* Styles all anchor tags with an href attribute */
}
Use Case: Highlighting all links on a webpage, even if their href attribute is empty.
2. [attribute="value"] Selector
Example:
input[type="text"] {
border: 1px solid black; /* Styles input fields specifically of type text
*/
}
Use Case: Styling specific input types in a form, such as text fields.
3. [attribute~="value"] Selector
Matches elements whose attribute value contains a specific word in a space-separated list.
Example:
[class~="highlight"] {
background-color: yellow; /* Styles elements with the word "highlight" in
their class attribute */
}
4. [attribute|="value"] Selector
Matches elements whose attribute value is exactly "value" or begins with "value-" (used
for language codes).
Example:
[lang|="en"] {
font-style: italic; /* Styles elements with lang="en" or lang="en-US" */
}
5. [attribute^="value"] Selector
Matches elements whose attribute value starts with the specified value.
Example:
a[href^="https"] {
color: green; /* Styles links that start with "https" */
}
Use Case: Differentiating secure links (https) from other types of links.
6. [attribute$="value"] Selector
Matches elements whose attribute value ends with the specified value.
Example:
img[src$=".jpg"] {
border-radius: 5px; /* Styles all images with .jpg extension */
}
Use Case: Applying specific styles to image formats like .jpg or .png.
7. [attribute*="value"] Selector
Example:
a[href*="example"] {
text-decoration: underline; /* Styles links containing the word "example"
*/
}
Imagine a signup form where specific inputs (e.g., email, password) need different visual
feedback based on their states. Using attribute selectors:
HTML:
<form>
<input type="email" placeholder="Enter your email" required>
<input type="password" placeholder="Enter your password" minlength="8"
required>
<input type="submit" value="Register">
</form>
CSS:
input[required] {
border: 2px solid blue; /* Highlights required fields */
}
input[placeholder] {
font-style: italic; /* Styles placeholder text */
}
input[type="password"][minlength="8"] {
border: 2px dashed orange; /* Indicates password criteria */
}
This ensures:
Practical Notes
1. Combine attribute selectors with other selectors (e.g., classes) for complex styling.
2. Be cautious with performance when applying attribute selectors to large documents.
3. Test selectors for cross-browser compatibility.