For sometime I’ve been evangelising about building Web sites with valid XHTML, using CSS for presentation and layout. I’m far from alone in this mission and the message is going in. However I’ve noticed that developers learning the new skills often end up with good CSS but poor XHTML. Specifically, the HTML code tends to be full of unnecessary divs and ids. This results in fairly meaningless HTML and bloated style sheets.
One of the prime goals of moving to XHTML/CSS is to make the HTML documents more meaningful by removing code such as
font tags – well
span are just as meaningless as
font. So I have this piece of advice for anyone switching to the XHTML/CSS way of coding:
- Don’t use divs or spans.
- Don’t use classes or ids.
Now before you turn away, branding me as a slave to semantics, I will explain some of the common misconceptions to show how the number of divs and ids can easily be reduced.
Use appropriate mark-up
Firstly, divs and classes are often used to replace more appropriate mark-up, classically headings:
The first line creates an
id for a heading. In the second example we see poor use of a paragraph (is ‘Sub heading’ really a paragraph?), resulting in the creation of a class. We could more meaningfully code these:
Style elements directly
Many folks equate CSS layout with using divs, but remember any style that can be applied to
div can also be applied to
blockquote and every other block level element. For example, forms are often floated to the right by wrapping them in a
div is not required as one can style the form directly:
This will apply the style to all forms. If this behaviour is not required then give the form an
Use cascading selectors
There is also a tendency to apply unnecessary classes and ids, for example:
Here the ‘field’ class is superfluous as we can apply style to every paragraph in the form:
So when can we use divs?
Divs should only be used when grouping related elements together. For example, a typical ezine page may contain a header, story, side bar and a footer. The story will contain a heading for the page and any number of paragraphs, tables, lists and so on, so it seems reasonable to wrap all of these in a div.
Similarly the sidebar may contain a list of related links and a feedback form; again it seems reasonable to group these together. Note that you still only need one div and one id for this as anything inside the sidebar can be selected specifically:
So here’s your mantra for today: ditch divs and eliminate ids for leaner, more meaningful mark-up. See also Standards don’t necessarily have anything to do with being semantically correct at Kottke, On Standards and Semantics at StopDesign and SimpleQuiz at SimpleBits, which are all generating good discussion on the subject.