CSS3 - Structural Pseudo Classes

The main use of pseudo classes prior to CSS3 was for links. The :link, :visited, :hover, :focus and :active pseudo classes restrict which <a> tags the style is to be applied to - for example the :hover pseudo class applies only to the link if the mouse cursor is over it and the :active pseudo class only applies if either hover applies and a mouse button is depressed or focus applies and the enter key is depressed.

The above pseudo classes have existed since CSS1. One further pseudo class was added in CSS2.1 and that was the first of the structural pseudo classes. :first-child allows you to apply styles specifically to the very first child element within the one identified before the colon.

CSS3 adds more structural pseudo classes.

The (n) in the above pseudo classes represents any number and so with just a simple (n) there the pseudo element would apply to every single element that matches the preceding criteria. The (n) can however ne replaced by an expression so as to identify which elements it is to apply to. (2n) would apply to every second element, (3n) to every third element etc. You can also add or subtract so (n+1) would apply to all elements except the first, (3n-1) would apply to the element before every third element (2,5,8 etc).You can also use the words odd or even in place of 2n-1 and 2n respectively.

Examples

tr:nth-child(2n) {background-color:#ccc;}

Limitations

The latest versions of all browsers will recognise these selectors. Earlier versions may not.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate