Tag Archives: selectors

CSS

CSS3 Selectors

While trying to answer a question on a forum today I found myself browsing the range of selectors available for CSS3. I’m late to the CSS3 party, having being bogged down in projects and due to my majority of my work audience using IE, but I like what I have found and feel good about the future.

In particular, I am cheered by the discovery of the first-child and last-child selectors:

Element:first-child
Element:last-child

Something I find myself doing very often is creating a list to contain navigation elements of page footer logos, and using padding to space these elements. I will then have to apply a class to the last element of a list (or sometimes the first) to cancel it’s padding. Consider this example:

CSS:

HTML:

Without the “last” class applied on the final list item, the list would be too wide for the container div and bad things would happen. Now it’s not going to to be a huge problem to add in this class, but I don’t like it for several reasons:

  1. It adds extra markup to the html.
  2. If the list is being populated dynamically, you have to an extra logic to ensure the class is added to the last item.
  3. If you want to add elements to the list on the fly, with AJAX for example, you have to move the class attribute.

Happily, the first-child and last-child selectors will make this small bug-bear a thing of the past, and I look forward to the day when CSS3 is widely supported enough for me to start using it. Come on IE, quickly now.