Translating Selectors

When writing or debugging CSS, it’s often helpful to describe a selector in plain English as a handy way to sort out things like inheritance and specificity, and just to better understand how the rules are being applied. If it doesn’t make sense when translated, there’s probably something amiss. Some examples:

p, li { ... } translates as “All paragraphs and list items.”

#content h3.subtitle { ... } translates as “All level-three headings with a class of ‘subtitle’ within an element with the id ‘content’.”

div#sidebar ul.menu:after { ... } translates as “The content immediately after any unordered list with the class ‘menu’ within the div with the id ‘sidebar’.”

body#mysite.contact a[href^="mailto"]:visited:hover { ... } translates as “Any link whose href begins with ‘mailto’ which is being hovered over and has been visited and is within the body element with the id ‘mysite’ which has the class ‘contact’.”

Of course, this is hardly a new idea. There’s even a handy-dandy online SelectOracle that will spit out translations of whatever selectors you feed it (assuming they’re valid). But I often find myself working backwards as well, describing in plain English what it is I want to select in order to construct the appropriate selector. E.g.; “I want to style all the level three headings in this box, but only on the pages in the ‘Company’ section” produces body.company #box h3 { ... }. Groovy.