Attribute Selectors

As well as being able to apply specific styles to those tags belonging to a particular class we can also apply specific styles just based on the HTML tag having a specific attribute present or perhaps having an attribute present that has a particular value. This enables us to avoid the need to go back an alter web pages to add class attributes if there is already something in all of the tags that can be used to identify them which both saves work and keeps our pages smaller.

div[id] {color:red;}

This stylesheet entry will change the colour of the text to red if that text is inside of a div tag that has an id attribute.

We can also test for a specific attribute value.

img[src="myimg.gif"] [margin:50px;}

This stylesheet entry will change the margins around each occurrence of the image "myimg.gif" on the page to be 50 pixels. Other images will not be affected. The content of the attribute must match exactly to that specified so the same image fully qualified with the domain name will not match.

If you want to test for just part of the content of an attribute then there are two further selector attribute options that you can use.

img[alt ~= "Steve"] {margin:50px;}

This one looks at the content of the attribute as a space separated list. If the specified value (in this example "Steve") appears at the start of the attribute followed by a space, at the end of the attribute preceded by a space or anywhere in between both preceded and followed by spaces then the entry will be applied.

We can also do the same for hyphen separated text.

p[lang |= "en"] {color:black;}

This example will apply to all paragraphs having a language attribute of English. This will match with en-US, en-GB etc.

Note that Internet Explorer 6 and earlier do not support attribute selectors.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow