Selective Enough?

Posted under: 

Are you being selective enough with your CSS? Maybe too much? CSS Selectors are the basis of good CSS. Inappropriate Selector choice is one of the most common sources of problems I find when troubleshooting CSS. The best strategy I know of is to start simple, and build on it. Don't start with obscure Class names, start with the type selectors. How can you define a Class meant to apply to paragraphs, if you haven't defined paragraphs? Define the basic HTML your site is built from before you add anything else.

For the sake of this discussion, let's define some simple HTML.

<div id="header"><div id="logo"><img></div><h1>Site Name</h1></div>

<div id="navigation">

<div id="content><h1>page title</h1>



Once you've defined the basics like h1, paragraph (p) , and lists (ul, li, ol, etc.), the next step is exceptions to those basics. This doesn't necessarily mean class tags yet, we can do better. Let's start with navigation. We've defined the basic unordered list CSS for the content section, but our navigation will also be a unordered list. While applying Class tags to the navigation lists would work, Descendant selectors are a better choice. If you use the styles "#navigation ul" and "navigation ul li" you can define you basic navigation list. Want another level? Use "#navigation ul ul". Using descendant CSS selectors allows you to use clean class-free HTML. Easy to write, easy to update.

Image selectors on the same HTML would be similar. Define the basic img style, then define exceptions. In this example "#logo img" or "#header #logo img" could be the exception.

You'll see a trend here. Keep it simple. Start with the basics, get a good foundation, then build on it. Maybe class selectors will be required, but they're not the place to start.

Add comment