This week’s question comes from Robert DiCello.
I was told that nested divs are not the best way to code. Is that correct?
Like many things regarding web design, it depends.
The most important thing to remember when marking up a document is the meaning of each element you use, and whether it is appropriate for the contained content. The
div element is simply a division of content; it has no particular meaning beyond that. A
p element, on the other hand, indicates that its contents form a paragraph. Similarly, a
li element indicates its contents constitute a list item.
There is nothing wrong with nesting
div elements, but it is possible to overuse or misuse the
div element. When we first made the move to CSS-based layouts from tables, it was common to see pages marked up with
div elements replacing every table, table row, and table cell that would have been used otherwise. This practice became known as “divitis,” or the overuse of
div elements should be reserved for instances where you need to wrap an element (usually for style or scripting purposes) around several block level elements (e.g.
ol, and, yes, even other
div elements). For HTML4 and under, the
div was the only tool we had for this purpose.
HTML5 introduces a new set of semantic elements that can be used in place of the generic
div elements we might have traditionally used in our documents. For instance, a site’s header (usually
div#head) would be better represented by a
header element. Similarly, a sidebar (traditionally
div#extra) might be more appropriate as an
For more on when to use these new HTML5 elements, we highly recommend consulting this handy flowchart/decision tree from HTML5 Doctor. You should also read our Sherpa review Making the Transition to HTML5.