suburban glory

A Blog in Suburban Glory:
Web Dev Ideas and Inspiration

A complete guide to CSS pseudo-classes

|| Category: CSS ||

CSS 2.1 pseudo-classes

a:link {color:#3344dd}
a:visited {color:#804180}
a:hover {color:#b50010}
a:active {color:#b50010}

The above CSS pseudo-classes should already be familiar to you, but if they aren't here is a brief explanation.

:link is the declaration for the link before the user has clicked on it. :visited is the state of the link after the user has visited the page it points to. :hover is the declaration for a link when the cursor moves over it. :active is the selected link

These are all used for styling links while :focus below is used for fields in forms.

This will give the field a yellow background when the cursor is clicked in the box:

input:focus{
background : #ffff00;
}

:focus is not support in IE6 and IE7 and :active is not supported in IE6 and only partially supported in IE7.

The five remaining CSS 2.1 pseudo-classes are below.

:lang(C)

Similar to the attribute selector, this pseudo-class will allow you to match your CSS in the language specified in the HTML document, like so:

:lang(en) p {
background : #ffffcc;
}

The above will give a yellow background behind all paragraphs that have either xml:lang="en" or lang="en" specified in the page.

:first-child

This is a useful CSS rule and it serves as an introduction to the myriad of CSS 3.0 pseudo-classes.

The only browser it doesn't work in is IE6. Here's how it looks in action and it does what you would expect:

p:first-child {
background : #ffffcc;
}
ul li:first-child {
background : #ffffcc;
}

The first block of code changes the background of the first paragraph while the latter does the same to first list item.

@page :first / @page :left / @page :right

These three are part of a number of CSS rules intended to create beautifully printed pages. They are quite arcane though and little used. For further information read this article here. They are only supported in a few browsers.

CSS 3.0 pseudo-classes

For me, this is where CSS becomes really very powerful and interesting. The key aspect of understanding this code is that it serves as a way of pinpointing certain elements on a page using only CSS and without adding any extra HTML.

I would suggest that this is about as complex as CSS gets at the moment so don't expect to pick it up immediately, let alone become fluent in its use after reading this article.

None of these work in any version of Internet Explorer but they all work in the latest versions of Opera, Chrome, Firefox and Safari. There is though a JavaScript solution to enable limited support in IE which is linked to at the bottom of this post.

:nth-child()

To demonstrate this pseudo-class lets say you have a list with five items. You need to style the third item and the third item only. If this is the case then use :nth-child() as below.

ul li:nth-child(3) {
background : #ffffcc
}

But it's more powerful than just this simple use.

ul li:nth-child(even) {
background : #ffffcc
}

ul li:nth-child(odd) {
background : #ffffcc
}

The above will target all even numbered list items and odd numbered lists respectively. I'm using lists as an example but it could just as easily be paragraphs, table columns or a variety of different purposes.

There's even a more precise use for :nth-child():

ul li:nth-child(3n+2) {
color: yellow;
}

Note the addition of the letter n. This is a number expression an+b and this will target the second and fifth list item and so on in a pattern of 3.

ul li:nth-child(4n+3) {
color: yellow;
}

Above will target the fourth and seventh list item and upwards in a pattern of 4.

Confused? The best way of understanding this is by creating a simple HTML list and playing around with this CSS syntax yourself.

:nth-last-child()

This is exactly the same as :nth-child() but it reverses the order, for instance the code below would target the last list item on a page:

ul li:nth-last-child(1) {
background : #ffffcc;
}

:nth-of-type()

As with :nth-child() this can either be a number, odd or even and a number expression; however, this matches a child of a specific element type while :nth-child() matches any child.

Again, lets give an example:

p img:nth-of-type(1) {
border : 2px solid #ffff00;
}

This will target the first image in any paragraph which :nth-of-type() is particularly useful for.

p img:nth-of-type(1) {
float : right;
}
p img:nth-of-type(2) {
float : left;
}

Above will float the first image in the paragraph to the right and the second image to the left.

The use of nth-of-type() over nth-child() allows more precision in targeting elements which need sometimes demands.

nth-last-of-type()

The same as :nth-of-type expect it selects from the bottom up. Below will give a border to the last image in a paragraph:

p img:nth-of-type(1) {
border : 2px solid #ffff00;
}

:last-child

The reverse of :first-child. Below will highlight the last item in a list:

ul li:last-child {
background : #ffffcc
}

:first-of-type and :last-of-type

What :nth-of-type() is to :nth-child(), so :first-of-type and :last-of-type are to :first-child and :list-child respectively.

:only-child

This targets a single child of its parents. Look at the following code:

#wrapper p:only-child {
background : #ffffcc
}

Above would give a background colour to the paragraph only if there was one paragraph in the wrapper div. It's a struggle to find an example where this would come handy. If you can think of one post it up below!

:only-of-type

Matches the only child element of its type. If you want to create a border around an image in a paragraph if there is only one image then use the following code:

p img:only-of-type {
border: 2px solid #ffffcc;
}

:empty

With this pseudo-class you can target an element with nothing in it. Maybe you are using a CMS and you want to hide a box until there is some user-generated content in which case you could use the code below. However, it's not particularly practical because even white space within the box would prevent it from working.

.box:empty {
display: none;
}

:target

This is a really useful little addition to the CSS library which allows styling when using fragment identifying in the URI.

Www.example.com#extra - #extra is the fragment identifier in this URI.

For a great tutorial on practical uses of :target read Craig Grannell's article Enhance Internal Page Links which appeared in issue #180 of net magazine

:not()

Also known as the negation pseudo-class this targets everything except that declared in the brackets. As an example this CSS will give every paragraph a yellow background except that with a class of highlight:

p:not(.highlight) {
background : #ffffcc;
}

:root

In a HTML document the root is html.

-----------

Now I'm going to show you some advanced CSS for forms which are a key constituent of most web sites.

There are two attributes in HTML that help restrict the users ability to input data into a field. They are disabled and readonly. For instance you may want to add disabled=”disabled” to the submit button until the user fills in all the required details. They are mostly only used in conjunction with JavaScript and CSS 3.0 allows styling of one of these – disabled.

input:disabled {
background : #ffff00;
}
input:enabled {
background : #ffff00;
}

The first example above would allows styling of all fields using the disabled attribute while the latter would affect fields not using it.

:checked

This is a useful little bit of CSS to use. It allows the styling of a form checkbox when it is checked. Below enlarges the box upon user interaction:

input:checked {
width: 20px;
height: 20px;
}

:indeterminate

This matches checkbox elements whose indeterminate DOM attribute is set to true by JavaScript.

:default / :valid / :invalid / :in-range / :out-of-range / :required / :optional / :read-only / :read-write

These are all for use with XForms, details for which read the Wikipedia entry

------------

It depends how you use the above CSS but if used thoughtfully and sensibly then I see no reason why you can't use most of it without worrying about IE users. What it will give users of the more advanced browsers is some extra subtle and pleasing aesthetics that if IE users don't see won't harm their use of your site.

However, as of January 2010, CSS3 pseudo-class selector emulation JavaScript has been released which allows some support in IE versions 5-8. Developer Keith Clark is responsible for this most welcome script and it works with all the main JavaScript libraries including jQuery, MooTools, DOMAssistant, Prototype, YUI and NWMatcher. I strongly recommend that you check out Keith's script.

-----------------

Epping Web Design

Comments

InkSketch || Wed 16th Jun 2010

This is great thanks. Much appreciated. (wishful thinking: would be even greater in a pdf :D)

TheContentBlock || Wed 16th Jun 2010

Thanks for the run-down on pseudo-classes. CSS is so powerful and some of these more obscure classes can really add to clean, smart code. Also, I wanted to address the following quote from your article:

Above would give a background colour to the paragraph only if there was one paragraph in the wrapper div. It's a struggle to find an example where this would come handy. If you can think of one post it up below!

This could definitely be a valuable pseudo-class in the case of dynamically generated content.

Damir || Wed 16th Jun 2010

:only-child would be usefull if there's e.g. only one post on a web page or only one comment to some post. Tnx for the article. It's the first time I saw some of these pseudo classes. This is going to my bookmarks.

Nilesh Shiragave || Wed 16th Jun 2010

Excellent. I never heard about some of the pseudo classes. Thanks for sharing this cool tutorial.

Anonymous || Thu 17th Jun 2010

An excellent article ! Honestly, I must say that I find the design of your web-site glaring and distracting, however.

best, Bill

Andy W || Thu 17th Jun 2010

Glad you liked it Bill

It is all pretty bright! :)

Sjoerd || Thu 17th Jun 2010

Thanks, awesome article =] One comment though, wouldn't the code below target the third and seventh items?

ul li:nth-child(4n+3) {
   color: yellow;
}

Above will target the fourth and seventh list item and upwards in a pattern of 4.

Andy W || Thu 17th Jun 2010

Yes, well spotted! I'll change it

shoaib || Fri 9th Jul 2010

nice tutorial,as m off with basics n m fluent with it......this will be nice for the arsenal of my knowledge n coding skills .thnx a lot for taking out time to explain it so nicely. n one more thing :- The captcha says :-Is ice hot or cold? lol

Kaden Hamilton || Tue 8th Feb 2011

Excellent! Very helpful tutorial!

-Kaden

You can add comments below.
Auto-paragraphing is enabled. Double newlines will be converted to paragraphs.

Allowed tags: a, abbr, acronym, b, blockquote, caption, cite, code, dd, del, dfn, div, dl, dt, em, i, ins, kbd, li, ol, p, pre, s, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, var.

If you wish add code examples then please do so between the following tags:

<pre><![CDATA[
Place code here
]]></pre>







mainland