You may remember that some HTML elements use attributes to add extra detail or functionality to the element. Some familiar attributes may be href
and src
, but there are many more—including class
and id
!
The attribute selector can be used to target HTML elements that already contain attributes. Elements of the same type can be targeted differently by their attribute or attribute value. This alleviates the need to add new code, like the class
or id
attributes.
Attributes can be selected similarly to types, classes, and IDs.
[href]{ color: magenta; }
The most basic syntax is an attribute surrounded by square brackets. In the above example: [href]
would target all elements with an href
attribute and set the color
to magenta
.
And it can get more granular from there by adding type and/or attribute values. One way is by using type[attribute*=value]
. In short, this code selects an element where the attribute contains any instance of the specified value. Let’s take a look at an example.
<img src='/images/seasons/cold/winter.jpg'> <img src='/images/seasons/warm/summer.jpg'>
The HTML code above renders two <img>
elements, each containing a src
attribute with a value equaling a link to an image file.
img[src*='winter'] { height: 50px; } img[src*='summer'] { height: 100px; }
Now take a look at the above CSS code. The attribute selector is used to target each image individually.
- The first ruleset looks for an
img
element with an attribute ofsrc
that contains the string'winter'
, and sets theheight
to50px
. - The second ruleset looks for an
img
element with an attribute ofsrc
that contains the string'summer'
, and sets theheight
to100px
.
Notice how no new HTML markup (like a class or id) needed to be added, and we were still able to modify the styles of each image independently. This is one advantage to using the attribute selector!
Instructions
To use the attribute selector to select the <a>
element with an href
attribute value containing ‘florence’, add the following code to style.css:
a[href*='florence'] { color: lightgreen; }
Notice how only the “Learn More” link in the Florence, Italy paragraph changed to light green.
Next, in style.css, use the attribute selector to select the <a>
element that has an href
attribute value containing 'beijing'
. Add a declaration of color: lightblue;
to make the link appear light blue.
Finally, use the attribute selector change the <a>
element that has an href
attribute value containing 'seoul'
to lightpink
.