Cleaner Code with CSS3 Selectors

23 Comments

Comments are ordered by helpfulness, as indicated by you. Help us pick out the gems and discourage asshattery by voting on notable comments.

Got something to add? You can leave a comment below.

  1. Andy Walpole

    I use attribute selectors in every and any form now. They are fantastic for usability / accessibility as they clearly highlight the field that the user is hovering over.

    All in all CSS3 (and 2.1!) is going to mean less HTML markup for presentation which has to be a good thing.

  2. Nathan Staines

    Excellent article, definitely one of my favourites for this years 24 ways to impress your friends ;)

    Can’t wait to start implementing some of the examples into my own site… it already feels like my life just got that little bit easier.

    Thank You!

  3. prisca

    Rachel
    thanks for such a detailed article and all your examples, brilliant :) I’ve shied away from some of your techniques in the past due to the poor browser support and my worries about relying on JS… will have to have another go now ;)
    Thanks :)

  4. Teddy

    Thanks for the insightful article! I have stumbled upon plenty of tutorials on how we can use selectors at their full power in the advent of CSS3 but I have to say that this is one of the most comprehensive one so far. What makes it so interesting is that you suggested using jQuery to cover up loopholes when it comes to dealing with old rusty browsers that fail to support such selectors.

    It’s a shame that IE6 and IE7 are illiterate when it comes to interpreting with these selectors but I’m glad that many are on the move to switch to a better browser – and one more cheerful, triumphant news is that Google released Chrome Frame for IE which will liberate many users locked down by corporate policies and nasty tech department folks that were forced to use IE6 (e.g. due to proprietary software used by the company and etc).

    Although I wouldn’t recommend using javascript to fix CSS issues due to the inherent problem that some (very few) users have javascript turned off for safety reasons, I have good faith that it still works for majority of those who are using older browsers. jQuery is a very valuable resource when it comes to dealing with CSS selectors :) thank goodness for that!

  5. Erik Vorhes

    A caveat: Internet Explorer 8 chokes on any CSS that includes a selector it doesn’t recognize, so it doesn’t respect this line of CSS from the “nth-child last-child” example:

    ul.gallery li:nth-child(3n), ul.gallery li.last { margin-right: 0; }

    To get IE8 to play nicely, you’ll need to change it to this:

    ul.gallery li:nth-child(3n) { margin-right: 0; }
    ul.gallery li.last { margin-right: 0; }

  6. Chris Rowe

    How about instead of using last-child do things on the other side of your objects (margin-left/border-left etc) and use the more widely accepted first-child?

  7. Chris Patterson

    Another approach to propping up selector support in legacy browsers is the SuperSelectors plugin I wrote a while back. It uses jQuery’s excellent CSS selector functionality to add support for a wide range of selectors, in any browser that’ll run jQuery. Classnames are totally customizable, and as of a week or so ago, it’ll even create the necessary CSS for you – so your stylesheets can be as pristine as your markup.

    Source is at http://github.com/chrispatterson/jquery-super-selectors – suggestions & patches are always welcome.

  8. Stewart McCoy

    Under the “Doing something something different with the last element” subheading, you write:

    “If each element has the right margin applied the margin on the final element will cause the set to become too wide forcing that last item down to the next row as shown in the below example…”

    However, the image below does not show the last element dropping to the next row, but it shows the result of applying a fix (e.g. putting a negative margin on the list).

    Shouldn’t the image show the last element dropping to the next row?

  9. Cool overview. CSS3 selectors rock… I use them all the time, specially in JS development. Just make sure you test that your library fully supports them cross-browser.

    I would definitely just add that you can use both :nth-child and :nth-last-child to achieve restrictions depending on the number of sibling elements.

    Have a look at:
    http://andr3.net/blog/post/142

  10. Mirko

    That’s excellent. I’ve been using the nth-Element in a 4 by 4 Thumbnail-Gallery and really needed to address the last Thumb in each row to remove the right-Margin (Just the Problem you described). No Problem with n-th-Element in FF and Safari. But I was stumped on how to make this work in IE without having to add a class to each of these Elements in the markup.
    With your jQuery Solution (which I didn’t thought of) you just made my day. :-) Thanks

  11. John Faulds

    How about instead of using last-child do things on the other side of your objects (margin-left/border-left etc) and use the more widely accepted first-child?

    That’s exactly what I do. I use Dean Edwards’ IE7.js as mentioned by Paul D. Waite which brings support for :first-child to IE6 as well and then add all margins, padding and borders on the left of elements.

    Using IE7.js you can also take advantage of the CSS2.1 selectors you talk about in your form example for IE6. The one area where I’ve had trouble has been targetting particular labels but I’m going to try out the htmlfor trick and see how it goes.

  12. Rachel Andrew

    I think if you are doing a lot of this then Dean Edward’s IE7.js is a good idea. Personally I tend to use JavaScript solutions for small enhancements on sites that already use jQuery for other things so it makes sense to me to just add in those selectors on a case by case basis rather than load in a bunch of stuff I am not going to need.

    I’d also suggest caution if developing with a library like IE7.js in place as it is very easy to then forget about the view of the site for users of IE6 with no JavaScript. Make sure you test with the library removed to make sure nothing breaks horribly.

  13. Josh

    I’m also very excited about pseudo selectors. They have proven to be very powerful in the jQuery that I’ve used on my site so far. I’ve not yet used them in any CSS as I’m waiting for more widespread browser support.

  14. Matt Wilcox

    While it’s a nice example of using CSS3 selectors may I point out a more backward compatible way of achieving the three wide grid using only CSS2, for those that need it?

    Instead of margin-right on the li elements, use margin-left, and then use a negative margin left on the ul to pull it into line, e.g.,

    ul { margin-left : -10px; }
    li { margin-left : 10px; }

    This allows you to create a grid with sides flush, but without requiring advanced selectors.

    Here’s a live example: http://mattwilcox.net/sandbox/edge-to-edge/edge-to-edge-alignment.html

  15. Martin

    Very useful article – particularly the details of the use of the nth-child. It is very frustrating having to add a class to every other row of a table hence the nth-child looks great. It also looks pretty useful for handling images. Is browser support any better yet?

  16. Wouter

    Nice article. The lack of support for these brilliant selectors managed to bug me during about every project I have worked on.

    Luckily with my current project I only have to care about Webkit, which by itself makes it a great project to work on :P, but with the next I may make good use of jQuery and be rid of one more source of annoyance. :) It still depends on the intended audience though, because using javascript can come with its own annoyances, as Prisca and Teddy mentioned.

    @Mike Breen:
    Good point. Although I think Rachel intentionally went for :nth-child() as jQuery filter, because it also accepts equations, like ‘3n’, instead of just ‘odd’ and ‘even’.

  17. Eric Clemmons

    I’d like to “second” the urge of caution when developing with libraries such as IE7, not so much because of the IE6/noJS incompatibility, but because of what the crutch does to you.

    For the majority of sites, the most crucial of elements (navigation, calls to action, etc.) should not require extra logic (Javascript) to function. Enhancement, of course, is perfectly acceptable.

    There was an article in recent news of how Yahoo! Sports had a syntax error in the minified Javascript served to users. Many sites would simply stop functioning or lose significant features. Yahoo! Sports continued working just fine, thanks to what many call Progressive Enhancement.

    As for using IE7 for fixing box-model issues with IE6, many CSS frameworks that support grid-based layouts (BlueprintCSS) take care of this already.

Impress us

Be friendly / use Textile