How To Use Attribute Selectors In CSS
Attribute selectors are, in my experience, rarely used. Thankfully though most modern browsers now support them, and with the new CSS 3 specifications some new features have been added to the already very useful attribute selectors.
Standard Attribute Selector
An attribute selector is used to select an HTML element using one of it’s attributes value. Let’s take a look at how that works:
1 2 3 |
a[rel="lightbox"] { background: #dfc97d; } |
So we have a standard element selector, followed by an attribute selector. The attribute selector is enclosed in square brackets, then the attribute name, a comparison operator (in this case an equals symbol), and finally the value to match in quotes. Let’s take a look at what the result would be using the code above. Tip: Use your browsers ‘View Source’ to see which hyperlinks have ‘lightbox’ in their rel attribute.
I am some text. I have a few links within me. Only one of those links have lightbox as the value of it’s rel attribute. Which one is it? Well it will have an orange background if your browser supports attribute selectors…
Complex Attribute Selectors
The 3rd CSS standard introduces some partial match selectors. I believe they have been available in some browsers for some time, but have only just been proposed to be added to the official CSS standard. Let’s take a look at them
Starting With…
You can select attributes that start with the selected value. It looks like this:
1 2 3 |
a[rel^="light"] { background: #dfc97d; } |
That would match ‘light’, ‘lightbox’, ‘lighter’, and any other words that start with light. It would not match something like ‘firelight’.
Ending With…
You can select attributes that end with the selected value. It looks like this:
1 2 3 |
a[rel$="light"] { background: #dfc97d; } |
That would match ‘firelight’ or any other words that end with light. It would not match words like ‘lightbox’, ‘lighter’, or any other words that start with light.
Value Contains…
You can also select attributes that contain the selected value. It looks like this:
1 2 3 |
a[rel*="ht"] { background: #dfc97d; } |
This will match any word that contains the letters ‘ht’.
Uses For Attribute Selectors
The uses for attribute selectors all depend on your project, however one specific use I can come up with is to place a special graphic in front, or change the background color of links that open in a lightbox. You could even use contains matching to identify links that go to external sites by matching http://
in the href attribute of hyperlinks. The rule will look something like:
1 2 3 |
a[href*="http://"] { //Do something here... } |
There we have it. I hope this quick look at attribute selectors has been helpful, if you have any questions or suggestions let me know using the comments.