In the CSS3 selectors module, the W3C introduced a new set of attribute selectors called substring matching attribute selectors for specifically targeting elements whose given attribute begins, ends or contains a certain value. In this article, we’ll learn how these 3 attribute selectors make our CSS more dynamic by allowing us to style elements without the need for additional classes or IDs.
Contents
“Begins With” Selector – [attr^="val"]
The “begins with” selector uses the caret (^) character to match an element with an attribute value beginning with the value specified in the selector.
For example, if we want to target all secure links beginning in “https”, we can do something like this:
a[href^="https"] { color: #FF6347; border-bottom: 1px dotted; }
Only those links containing “https” at the beginning of their href
values are selected.
“Ends With” Selector – [attr$="val"]
The “ends with” selector uses the dollar sign ($) to match an element with an attribute value ending with the value specified.
This selector might be useful for adding an icon next to a link based on a file extension in the href
attribute’s value.
<a href="details.pdf">Details</a>
In our CSS, we can create the following rule:
a[href$=".pdf"] { background: url('images/pdf.png') no-repeat 0 2px; padding-left: 25px; }
The PDF file icon will be rendered next to the link because the browser will match the href
string ending with “.pdf”.
“Contains” Selector – [attr*="val"]
Finally, the “contains” selector uses the asterisk character (*) to match an element with an attribute value containing at least one instance of the value specified.
Let’s say we need to select all thumbnail images, which are located in a directory named “thumbnails”.
<img src="images/thumbnails/dog.jpg" alt="Sparky" />
In our CSS, we can select only those images containing “thumbnails” anywhere in the src
attribute’s value.
img[src*="thumbnails"] { border: 5px solid #000; }
Browser Support
The good news is these attribute selectors are widely supported in all modern browsers (including IE7+).
As we just learned, substring matching attribute selectors allow more granularity by letting us select elements based on individual attribute values, so let’s keep these in mind when styling our pages.
Selectors are patterns that match against elements in a tree,
and as such form one of several technologies that can be used to select
nodes in an XML document.
Web
Developers NYC
Thanks for the tips! Did not know this was possible.
Chears
Good Post Guil.
Regards : Farhan