CSS3 attribute selectors tutorial

CSS3 attribute selectors now can select substrings within an attribute value. What does this mean and when this feature is useful? This is actually the topic of this post, where I'm going to discuss with you such features in details. One key thing to remember before starting is this: always ask yourself if a new CSS feature is really useful for you and your work, that is, your daily work as a web developer using CSS. If it's unlikely that you'll ever use this feature, don't even bother spending time to learn it. Learn it only when you need it. Now let's get started.

Substring matching

An attribute's value is simply a string, like this:

http://www.site.com/article/article.html
or
class1 class2

Both these strings can be actually split into substring, such as:

  1. http
  2. ://
  3. www
  4. .
  5. site.com
  6. /article/
  7. article
  8. .html

Now imagine this string inside the href attribute of a link:

<a href="http://www.site.com/article/article.html">Link</a>

CSS attribute selectors are said to be substring matching selectors, because they're able to select an element based on the presence of one or more of those substrings we saw earlier. Their syntax is:

CSS3 attribute selectors
Syntax Meaning
element[attribute^="substring"] Selects an element when its attribute's value starts with the given substring
element[attribute$="substring"] Selects an element when its attribute's value ends with the given substring
element[attribute*="substring"] Selects an element when its attribute's value contains the given substring, in any position it occurs

Examples

Let's get back to our link:

<a href="http://www.site.com/article/article.html">Link</a>

We can select this link by checking if its href attribute starts with http:

a[href^="http"] { }

or if such attribute ends with .html:

a[href$=".html"] { }

or even if the URL contains the word site in any position:

a[href*="site"] { }

This is useful for styling hyperlinks, but it turns out to be even more useful with attributes that contains multiple values:

<p class="test1 test2 test3">Test</p>

We can select this element by checking whether its class attribute contains the substring test:

p[class*="test"] { }

As you can see, there are many possible use cases for CSS3 attribute selectors.

Browser support

CSS3 attribute selectors are currently supported in the latest versions of Firefox, Chrome, Opera and Safari. Internet Explorer supports them as of version 7.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.