05/22/2013 - 1 comment.

Substring Matching Attribute Selectors

Using substring matching attribute selectors, enables you to add very specific and powerful CSS styling to a page without adding any nasty, non-semantic HTML. I've found that this advanced CSS selector technique is best demonstrated within the common situation of adding colored social media links to your website. As an example, let's say I want two social media links in my footer; each colored with the site's respective primary branding color. Traditionally, I would target each of these elements, with an ID:

HTML
<a id="fb" href="http://facebook.com/example/"> Facebook</a>
<a id="tw" href="http://twitter.com/example/"> Twitter</a>

CSS
a#fb {color:#3b5998;}
a#tw {color:#2BA9E1;}

Now, this same example, using substring matching attribute selectors. I simply target the href using the following code:

HTML
<a href="http://facebook.com/example/"> Facebook</a>
<a href="http://twitter.com/example/"> Twitter</a>

CSS
a[href*='facebook'] {color:#3b5998;}
a[href*='twitter'] {color:#2BA9E1;}

Now, while targeting "facebook" or "twitter" as a part of the href value works for a small, controlled website, I would be much more specific with my targeted href values on a larger website. The problem is that this could easily cascade and override other links, causing unintended styling.

There are other attribute selectors that can be used instead of the "*" character, which itself indicates a Contains selector.
Here's a quick reference:

  • ^ Begins With Attribute Selector. This indicates the string begins with the specified value.
  • $ Ends With Attribute Selector. This indicates the string ends with the specified value.
  • * Contains Attribute Selector. This indicates the string contains at least one instance of the specified value, in no order.

The Ends With Attribute Selector is especially useful to target links ending with a specific file extension. You could add icons to these links, indicating visually to the user that they are, for example, clicking on a .pdf vs a .doc file.

Substring matching attribute selectors are a powerful tool to have in your toolkit, as it provides much opportunity and helps to avoid the use of non-semantic HTML. As a bonus, these special selectors have very strong support in all modern web browsers!

Looking for an example? Hover on the social media icons in the footer of this page!

Published by: Ray in Best Practices, CSS