Super CSS, the power of the selector

October 15, 2008

We all love CSS it’s fundamental to the web. However most of us do not use the full power of CSS. A quick rummage around the W3C specification and you will see how powerful CSS can really be. I’m talking about the CSS selector, sure we all use the basic selectors, but what about the more complicated ones.

Well here’s my guide to the most useful not very used CSS selectors (as well as what they are currently supported in).


Pattern Meaning IE6 IE7 FF SF OP
E > F Matches any F element that is a child of an element E.
E:first-child Matches element E when E is the first child of its parent.
Matches element E if E is the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited).
Matches E during certain user actions.    
E + F Matches any F element immediately preceded by an element E.
E[foo] Matches any E element with the "foo" attribute set (whatever the value).
E[foo="warning"] Matches any E element whose "foo" attribute value is exactly equal to "warning".
E[foo~="warning"] Matches any E element whose "foo" attribute value is a list of space-separated values, one of which is exactly equal to "warning".


Pattern Meaning IE6 IE7 FF SF OP
E ~ F Matches any F element preceded by an element E.
E:empty Matches element E where E has no children, including text nodes  

If you need a detailed walkthrough on how these selectors work, please refer to the W3C Specification on CSS3 Selectors (which includes all the CSS2 selectors).

A Couple of Examples

I couldn’t just give all these CSS selectors without giving you some great examples of how they can be used.

E:first-child/E:last-child – You have a ul list of elements which you float horizontally. With first child and last child you can easily set the margins for the first and last child different from the remaining items:

ul { list-style: none; margin: 0px; padding: 0px; }
ul li { float: left; margin: 0px 10px; }
ul li:first-child { margin: 0px 10px 0px 0px; }
ul li:last-child { margin: 0px 0px 0px 10px; }

E:empty – You may have a situation where you have an empty paragraph. Paragraphs will always have a margin top and a margin bottom, which could look unsightly. So lets remove it.

p:empty { display:none; }


comments powered by Disqus