CSS attribute selectors are powerful tools that allow you to target HTML elements based on their attributes or attribute values. They provide a flexible way to style specific elements without relying solely on classes or IDs.
Attribute selectors use square brackets [ ] to define the selection criteria. Here's the general syntax:
[attribute] { /* styles */ }
[attribute="value"] { /* styles */ }
[attribute~="value"] { /* styles */ }
[attribute^="value"] { /* styles */ }
[attribute$="value"] { /* styles */ }
[attribute*="value"] { /* styles */ }
input[type="text"] {
border: 2px solid #ccc;
padding: 5px;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
This example styles text inputs with a border and padding, while submit buttons get a green background and white text.
a[href^="https://"] {
color: #00a;
font-weight: bold;
}
a[href$=".pdf"] {
background: url('pdf-icon.png') no-repeat;
padding-left: 20px;
}
Here, we style external links (starting with "https://") in blue and bold, and add a PDF icon to links ending with ".pdf".
While attribute selectors are powerful, they can be slower than class or ID selectors. For optimal CSS Performance Optimization, use them judiciously, especially in large stylesheets or on performance-critical pages.
CSS attribute selectors offer a flexible and powerful way to target elements based on their attributes. They're particularly useful for styling form elements, links, and other elements with specific attributes. By mastering attribute selectors, you can write more efficient and maintainable CSS code.