Attribute Selectors

Attribute selectors selects an element base on the presence or value of an attribute. Attribute selectors are particularly useful when working with links or form inputs. Attribute selectors can come in many different flavors, 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 no or a false value, will be selected.

/* <a> with a title attribute */
a[href] {
  color: 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 desire 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;
}