Explaining CSS Selectors Part II

See last weeks post for part one of Explaining CSS Selectors.

Attribute Selectors

Attribute selectors allow you to target a group of items on a page by matching a particular attribute. This opens up a whole new method of selecting your targets. Unfortunately attribute selectors are not supported in IE6 (which is why they’re not very commonly used), and IE7’s support is a bit buggy at times, however with IE8 out today, hopefully support for these selectors will be greatly increased and we can finally get away from being held back by supporting IE6 users.

Attribute selectors can be used in a number of ways. You start with either a HTML selector or the universal selector (*) followed by the attribute selector within square brackets ie.

[sourcecode language=”css”]img[alt] { border: 2px solid red; }
img[rel=”external”] { border: 2px solid blue; }
img[alt~=”photo”] { border: 2px solid green; }
p[lang|=”en”] { color: red; }[/sourcecode]

Going through the methods above:

  1. This will give any image on a page a red border if the image has an alt attribute
  2. This will give any image with an attribute of rel that has the exact value of external, a blue border
  3. This will give any image with an alt attribute whose value contains the word photo somewhere in it, a green border
  4. This will set any paragraph of text to be red, if it has been assigned a language attribute whose value starts with ‘en’ followed by a hyphen and then usually further information eg. en-US or en-GB


Pseudo-classes allow you to target even more specific elements on the page. We’ve seen some of these before however I’ll cover them all below.


The first-child pseudo-class matches an element that is the first child element of another element. For example, to target the first list item in a list you could use

[sourcecode language=”css”]ul li:first-child { margin-left: 20px }[/sourcecode]


Allows you to specify the properties for an unvisited anchor link eg.

[sourcecode language=”css”]a:link { colour: blue; }[/sourcecode]


Allows you to specify the properties for a visited anchor link.

Dynamic pseudo-classes

There are 3 dynamic pseudo-classes that are usually activated by a user on the page. The 3 selectors are

Activates when the user hovers their pointer over an element on the page eg. a link
Activates when the element has focus
Applies when the element has been activated

Next week I’ll cover the last of the selectors, the pseudo-elements, and also give some every day examples of using these more advanced selectors.


Disclosure: In full disclosure, it is safe to assume that the site owner is benefiting financially or otherwise from everything you click on, read, or look at while on my website. This is not to say that is the case with all content, as all publications on the site are original and written to provide value and references to our audience.

One Response

  1. Play Games Win Prize March 21, 2009