How to write better CSS

by James

Well-written CSS is easier to read, easier to maintain, and generally less of a headache. But the key to better CSS isn’t in brackets and line breaks: it’s actually all about the HTML.

CSS what-now?

We all know about Cascading Style Sheets. The W3C calls CSS:

a simple mechanism for adding style (e.g. fonts, colors, spacing) to Web documents.

A nice, clear definition which puts the focus on the important distinction between styles and documents.

Now, you already know not to put styling in your HTML (unless it’s within style attributes): font, link, vlink and other tags which directly styled documents have gone the way of tables-for-layout — keeping these anachronisms out of your markup will help you no end. But more than that, well-structured HTML will help you to write cleaner, more concise CSS.

Let your markup lead the way

A lot of people, when marking up a blog, will do something like this:

[html]
<html>
<body>

<h1>My Cool Blog</h1>

<div class="article">
<h2 class="title">Lorum Ipsum</h2>
<p class="meta">posted by John, 10/8/09</p>

<div class="body">
<p>…</p>
</div>
</div>

</body>
</html>
[/html]

All well and good (and nicely semantic), but a lot of those classes aren’t actually necessary for CSS: it’s easy to stuff your markup full of classes and IDs, but in many cases the structure of the document itself will allow you to apply style rules just as easily.

Look Ma! No classes!

Try this on for size:

[html]
<html>
<body>

<h1>My Cool Blog</h1>

<div>
<h2>Lorum Ipsum</h2>
<p>posted by John, 10/8/09</p>

<div>
<p>…</p>
</div>
</div>

</body>
</html>
[/html]

Now maybe your CSS brain is screaming ‘NO!’, but this will work just as well when it comes to CSS:

[css]
h1 {
font: 20px helvetica;
}

body > div {
border-top: 1px solid #000;
}

/* article titles */
body > div > h2 {
color: red;
}

/* article meta-data */
body > div > p {
color: #ccc;
}

body > div > div {
/* CSS for article bodies here */
}
[/css]

Maybe not the most attractive blog in the world, but those selectors work! See how we’re using descendant selectors to reflect the structure of our HTML? No need for classes or IDs, and the well-structured markup will give future developers a clue as to the relative importance of information inside the HTML document, too.

In conclusion…

Thinking carefully about the structure of information in your HTML will help your write clear, concise, well-structured markup and CSS. Try it!