Attribute Selectors
Attribute selectors selects an element based on the presence or value of an attribute. Attribute selectors are particularly useful when working with links or form inputs. Any attribute can be used with this selector, but all of them are surrounded by a set of square brackets []
.
The most basic attribute selector merely searches for the presence of the attribute on an element. Any matching element with attribute, even if the attribute has non or false value, will be selected.
/* any <img> tag with aria-label attribute */
img[aria-label] {
border: 1px solid green;
}
It is possible to select only those elements with specific value of attribute. This is accomplished by proceeding the attribute name with an equal sign and desired value. The value must also be in quotes. Only elements whose attribute value matches exactly to the desired value will be selected.
/* <a> with href value of "https://algonquincollege.com" */
a[href="https://algonquincollege.com"] {
color: green;
}
Finding an element by its attribute value can be limiting, it is more practical to see if the value begins, ends, or contains the desired value. All three of those can be accomplished using the following syntax.
^=
for begins with
*=
for contains
$=
for ends with
/* <a> with href that begins with "http" */
a[href^="http"] {
color: green;
}
/* <a> with href that contains "abc.com" */
a[href*="abc.com"] {
color: blue;
}
/* <a> with href that ends with ".pdf" */
a[href$=".pdf"] {
color: red;
}