Power CSS3 – Attribute Selectors

This tutorial will cover a detail description about the capability of Attribute Selectors in CSS3. Before starting don’t forget to check these two prior articles in this series.

1. universal, type, id and class selectors
2. Descendant, Adjacent, Child, Sibling Combinators and Selectors

Power CSS3 – Attribute Selectors

The attribute selectors target elements based on the presence of HTML attributes and/or it’s value and are declared using square brackets.

1. X[attribute]

This will match all input elements with an attribute of type, regardless of the value including button. radio, text and other as well. Let’s see one more example:

This will only select the anchor tags that have a title attribute.

Note: There should not be a space before the opening square bracket unless you intend to use it along with a descendant combinator like X Y[attribute].

View Demo | Compatible with: IE7+, Firefox, Chrome, Safari, Opera

Now what if we need to target elements with more specification? Well, keep reading

2. X[attribute=”value”]

This CSS3 selector would match the following element:

But wouldn’t match with:

View Demo | Compatible with: IE7+, Firefox, Chrome, Safari, Opera

Now let’s take advantage of some fine twists in this attribute – value pair selector.

3. X[href=”url”]

All the anchor tags which link to http://fellowtuts.com will be styled with the specific color where as ll other anchor tags will remain unaffected.

Remember to wrap the value in quotes when using a JavaScript CSS selector engine as we are doing in CSS rule. Always use CSS3 selectors over unofficial methods whenever possible.

View Demo | Compatible with: IE7+, Firefox, Chrome, Safari, Opera

4. X[href*=”text”]

This broad statement targets all those anchor tags which have value yahoo somewhere in their href attribute. That way, this selector is covering yahoo.com, mail.yahoo.com and yahoomail.com.

View Demo | Compatible with: IE7+, Firefox, Chrome, Safari, Opera

5. X[href$=”.jpg”]

Style all anchors which link to, say, a photo through searching for the end of string. Here we’re searching for all anchors having at least a url that ends with .jpg or rather say, which link to an image. Keep in mind that this certainly won’t work for gifs and pngs. So what is the solution? Check the next one.

View Demo | Compatible with: IE7+, Firefox, Chrome, Safari, Opera

6. X[data-*=”value”]

Use a custom attribute as selector that would work for other type or images as well and no need to create multiple selectors for each image type like a[href$=".png"]. Now the html is:

View Demo | Compatible with: IE7+, Firefox, Chrome, Safari, Opera


Hope you are enjoying the series. the last part pseudo-class and pseudo-element will light up the advance selectors pseudo-class and pseudo-element.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.