CSS 3 Attribute Selectors and Substring Matching Attribute Selectors
Dr. Foltz
December, 2020
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.
- ^ = begin
-
- = contain
- $ = end
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;}