CSS Attr Selectors
CSS Attribute Selectors
CSS attribute selectors allow you to target elements based on their HTML attributes or attribute values. This is useful when elements do not have classes or when you want to style elements based on specific attribute patterns.
Basic Attribute Selector
The simplest form selects elements that have a specific attribute.
input[type] {
border: 1px solid #ddd;
}
This rule selects all input elements that have a type attribute.
Attribute Equals Selector
You can select elements where the attribute value exactly matches a value.
input[type="text"] {
border-color: #1f4bd8;
}
Attribute Contains Selector
The *= selector matches elements whose attribute value contains a specific string.
a[href*="docs"] {
font-weight: bold;
}
This selects all links that contain the word docs in their URL.
Attribute Starts With
The ^= selector matches attributes that start with a specific value.
a[href^="https"] {
color: green;
}
This selects secure (HTTPS) links.
Attribute Ends With
The $= selector matches attributes that end with a specific value.
a[href$=".pdf"] {
color: red;
}
This is useful for styling download links.
Attribute Selector Example
Consider the following HTML:
<a href="guide.html">Guide</a> <a href="manual.pdf">Manual</a> <a href="https://example.com">Website</a>
a[href$=".pdf"] {
font-weight: bold;
}
a[href^="https"] {
color: green;
}
Code Challenge
Goal: Style links differently using attribute selectors.
HTML:
<a href="page.html">Internal Page</a> <a href="file.pdf">Download PDF</a> <a href="https://example.com">External Site</a>
Task:
- Make PDF links bold
- Color external links green
- Keep normal links unchanged
Try a Solution:
a[href$=".pdf"] {
font-weight: bold;
}
a[href^="https"] {
color: green;
}
What’s Next?
Next, you will learn how to style forms using CSS.