CSS3 Attribute Selectors
The attribute selectors allow the designer to select HTML elements with specific values.
The following example will place a green border around every image that has an alt attribute.
HTML <img src="image.jpg" alt="image">
CSS img[alt] {border: thick solid green};
Specific values may also be selected.
HTML <img src="image.jpg" alt="wow">
CSS img[alt="wow"] {border: thick solid green};
Missing values can be targeted using the :not() selector. The following example will target any image with an empty alt attribute.
HTML <img src="image.jpg">
CSS img:not([alt]) {border: thick solid red};
Substring Matching Attribute Selectors
The substring matching attribute selectors essentially act like wildcards and allow the designer to select elements based on partial attribute value matches.
The designer can specify the location within the value to be matched.
- [] list the attibute to select if that attribute exists
- = exact match
- ^ = begin
- * = contain
- $ = end
- ~= value contained in a space-separated list
- |= value contained in a dash-separated list
Example
HTML
<p class=”mybigpicture”>text</p>
<p class=”mystuff”>text</p>
<p class=”picture”>text</p>
CSS
The following CSS will apply a border to any paragraph with a class where the class name begins with the letters my.
p[class^="my"] {border: thick solid black;}
Alternatively, the following CSS will apply a border to any paragraph with a class name containing the letters picture in any location.
p[class*="picture"] {border: thick solid black;}
Using the $ allows the designer to select only paragraphs where the class name ends with the letters picture.
p[class$="picture"] {border: thick solid black;}
The A rel Attribute (HTML)
The anchor statement supports a useful attribute named rel (for relationship). This attribute defines the relationship between the current and listed/linked document. Acceptable values include alternate, author, bookmark, external, help, license, next, nofollow, noreferrer, noopener, prev, search, and tag. The rel attribute can be referenced by the attribute selectors.
The data- attributes (HTML)
HTML elements often have attributes that can assume specific values; however, an author can create their own attributes! These must begin with data- to be valid. In other words, data-keywords might be a valid attribute. After creating those, the author could use the selectors listed above to select specific items.