Amber Weinberg: Freelance Web Developer specializing in semantic WordPress, Mobile, CSS and HTML5 Development

The Blog

Less HTML is Better HTML: Simplicity in Coding

Posted on 10/20/09 in blog, development about , ,

Today’s post has been co-written by a Twitter friend of mine, Colin (@chief27). Bio below post.

Amber: I’ve found that many beginning web developers tend to overuse divs, id’s and classes. While this can be a great crutch at first, it’s necessary once you’ve gotten the HTML and CSS basics down to really begin honing your abilities. One way to make your coding stand out from the crowd is to minimize it and use as less of it as possible. By using less code, your code not only looks cleaner, it tends to be more semantic (less code to potentially have errors in), quicker to load and more professional (no one wants to have a messy birds nest behind their nice design).

Colin: Having made the transition from beginner (X)HTML/CSS developer a bit more recently than Amber, I have to say I completely agree. When web developers start out they litter their code with divs, ids and classes. I know this because I used to do it too. Nowadays, I like my code to be clean and ordered so that it can be easily read and comprehended, so I’ve stopped overusing divs, ids and classes. Something else Amber touched on, that develops as you learn (X)HTML/CSS, is the understanding of (X)HTML semantics. When we speak of semantics in (X)HTML we talk about using tags which describe the meaning of their content. Essentially this is the purpose of the (X)HTML language, to describe the contents of a document. This is important for screen-readers and search engines which rely on the (X)HTML tags used to properly describe how the document should be interpreted.

The Difference Between Divs and Tags: Semantics

Colin: So we’ve both said that too many divs are bad, but how do you know when you’re using too many divs? When you start wrapping divs around tags which have a semantic description, or when you start using divs in place of semantic tags, it’s usually a good indication that you’re using too many divs. Div tags have no semantic description, they are used to divide (or section off) areas of the website which cannot be described by other html tags.

Dividing Layouts

Colin: The best way to approach this is to take a hierarchical view of the website, identifying the main “sections”, identifying the content that will go inside these sections and selecting the most appropriate tag for that content from a tag list such as the w3c tag list. I’ll come back to the tag list a little later on but for now let’s try and identify the main sections of the website from a top-level.

A standard 2 column layout, with main content in the left-hand column and a sidebar in the right can be visualized like so:

clip_image001

As of HTML 4.01 and/or XHTML 1.1 we do not have any tags which describe these sections, therefore, they must be divs. In the diagram I gave each of these sections a name, this name corresponds to the id of each of the divs.

  • <div id=”header”></div>
  • <div id=”main-content”></div>
  • <div id=”sidebar”></div>
  • <div id=”footer”></div>

It’s good practice to give each of your divs an id and of course it must be a meaningful name which describes the contents of the div.  Remember a div has no semantic description by itself, but by giving it an id you are giving it an implied meaning which you can use in your css.

Amber: Right, Colin. Also, it’s important to remember, that if we correctly assign our CSS rules to the divs; that you’ll actually need less of them to get your content laid out correctly. For beginning developers, the tendency is to stick multiple wrapper divs around the content divs in order to get them to “align with each other” (This does not apply to the main container div you use to center all your content in a browser). However using floats easily corrects this problem without the use of a wrapper div. In Colin’s example above, you see we only have 2 content divs, main-content and sidebar. The n00b practice would be to stick both of these inside a wrapper div:

<div id="header"></div>

<div id="middleSection">
.....<div id="main-content"></div>
.....<div id="sidebar"></div>
</div>

<div id="footer"></div>

For OCD organizers like myself, I can understand this need to neatly compartmentalize all your divs into sections, but it’s unnecessary and adds to the load time of your HTML. Instead you should float your main-content left and your sidebar right, which organizes like this in the HTML:

<div id="header"></div>

<div id="sidebar"></div>
<div id="main-content"></div>

<div id="footer"></div>

See, you’ve already shortened your HTML by a few lines.

Dividing the Content Within a Section

Colin: Now that we have visualized the sections of the website from the top-level, let’s move on and breakdown the header section. This should hopefully be enough to illustrate the benefits of using a minimal number of divs, id and classes and more importantly, how to do it.

To keep this example simple I’m going to say that our header has the following components:

  • A logo
  • The website name
  • Navigation

Amber: Without using these principals, the typical HTML code for something like this would look like:

<div id="header">

.....<h1 class="name">Website Name</h1>
.....<div class="logo"><img src="images/logo.jpg" alt="Logo"/></div>

.....<ul id="nav">
..........<li class=”current”><a href=”./home.html”>Home</a></li>
..........<li class="navItem"><a href=”./about.html”>About</a></</li>
..........<li class="navItem"><a href=”./contact.html”>Contact</a></</li>
.....</ul>

</div>

Colin: Now many beginners would be tempted to say: “3 sections, that means 3 divs”. But if we look at w3c tag list we can identify 3 tags which do a far better job of describing the content of each of these components. Remember a div is a tag without a semantic description. Therefore, an <img> tag better describes the logo; the website name is better described by an <h1> tag and navigation can be better described by a <ul> tag.With these tags in mind, the header section may look like this:

<div id=”header”>

.....<h1>Website Name</h1>
.....<img  src=”./images/website/logo.png” alt=”Website Logo” />

.....<ul >
..........<li class=”current”><a href=”./home.html”>Home</a></li>
..........<li><a href=”./about.html”>About</a></</li>
..........<li><a href=”./contact.html”>Contact</a></</li>
.....</ul>

</div>

Use Less Ids and Classes By Implementing Selectors

Colin: Something you may notice about this code is the distinct lack of ids and classes. This is the advantage of splitting your website into sections and then breaking down each of the components in that section. If you consider your design and properly structure your content you do not need to give elements such as the <h1> tag an id because you know that the only <h1> tag inside the div with id of header is the website name.

In your css these elements would be accessible using the following selectors

  • #header h1 {}
  • #header img {}
  • #header ul {}
  • #header ul li {}
  • #header ul li a {}
  • #header ul li a:hover {}
  • #header ul li.current a {}

Note the use of the css pseudo class hover to define the hover state of the menu item.

Also note how the css class “current” is applied to the menu. Beginners may be tempted to select the “current” class by using :

.current {}

Functionally this works, but it now limits the scope of the “current” class. This becomes an issue if you are working on a large site or working with a number of developers and one of you inadvertently applies the “current” class to another tag. By using css selectors which specifically state that this style should only be applied if an <li> tag, inside a <ul> tag, within the header div, has a class of “current”, it allows you to use the “current” class on another tag to provide an entirely different style.

Amber: LOL You’re even more minimized than I am! But you’re absolutely right, that everything does NOT need a class. Unfortunately, sometimes IE6 requires a height and width on the images to display properly, so you’re almost always forced to give your image a class, however if there’s just one, or they’re all the same in one div, it’s a great code saver to target all of them with #div img, as in Colin’s example above.

Conclusion

Amber: While none of these specifically save space in the CSS (that’s another post) these cut down on HTML length dramatically. It also makes it easier to update, as you won’t need to swim through useless code to find one thing to update. And one final benefit from me, when you need to change something (i.e. the navigation), you don’t have to reopen your HTML to add or delete classes, you can target them using you selectors.

About Our Guest Author

Colin McCormick – Is a 20 year old Web Systems Development student studying at Glasgow Caledonian University. He has skills in (X)HTML/CSS, PHP, Javascript, Python, Java. He has a passion for usable and accessible web experiences and when he grows up….he’s going to make the web a better place (x)
Follow him on Twitter.

About the author
Amber Weinberg specializes in clean and semantic XHTML, CSS and WordPress development. She has over 10 years of coding experience and is pretty cool to work with. Amber is available for freelance work, so why not hire her for your next project?

13 Awesome Comments

  1. I tend to create extra divs for ease of design later on down the road. My skeleton typically looks like [code]

    Company Name

    ©

    [/code]

    It’s a bit more divs that the methods suggested but when you are working with complex drop shadows and background imagery, you need some nested divs to pull this off.

    Look at how CSS ZenGarden does this with extra wrapper divs. In a recent development, I even used 2 extra wrappers around the page for a flexible width with shadows on either side while keeping the page in the center.

    I do believe new developers, or poorly disciplined developers, can go overboard, I have found this to be the most flexible method as far as margin and padding control with background images.

  2. Outstanding post! Some great tips on reducing XHTML overhead. I would add that it’s important to do your markup before you style it. I’ve found that to be the easiest way to ensure you use tags in a semantic fashion and avoid the dreaded “div-itis”.

  3. Amber says:

    @Anthony Of course, when there is a need for nested divs, for complicated bkgs, etc, that’s ok. We were more talking of empty container divs that only server to “wrap” unnecessarily around elements.

    @Jason Agreed, I also do my HTML and make sure it’s validated, etc before I start my CSS. Good way to keep organized, and somehow it’s actually made my coding a good 2x faster.

  4. Good article Amber!! They call the overuse of divs “divititis”.

    @colin The best way to approach this is to take a hierarchical view of the website, identifying the main “sections”,

    I agree. People should start visualizing how websites are created. Created into sections. Column, column, column etc.

  5. @Amber Thanks for asking me to guest blog :D

    @Anthony At the minute extra divs for the fancy effects are a necessary evil. With HTML 5 and CSS 3 and future developments of the two technologies, we will hopefully, someday, reach the truly semantic web envisaged by Tim Berners-Lee.

    @Jason Garrison Thanks, taking a little credit :P . I agree, to an extent. I have my boiler-plate templates which have the (x)html ready to go and I do narrow down the main content sections. But after you’re used to doing this I think you can get away with developing the (x)html and the css side by side. It’s all down to you though really, find what works best for you and stick to it.

  6. Polprav says:

    Hello from Russia!
    Can I quote a post in your blog with the link to you?

  7. Amber says:

    @Polprav Yes, please credit me with my name and a link backto my site :)

  8. Isaac says:

    Alright, well, there are some good points about “divitis” in here and wrapping floated divs but, at the same time, I saw no mention of clearing those floats. It’s essential to clear your floats, rather than assigning dimensions that will just slide them all together magically; otherwise, changing or adding something later can be a bit of a hassle. It also gives a visual point of reference to say “I know these divs are floated, they’re cleared here, here is where my document flow starts again”.

    The part that I wholeheartedly disagree with is the excessive use of descendant selectors. I don’t have a reference link handy (hoping someone will be outgoing enough to find a good one), but descendant selectors take longer to parse than more exact selectors like id or class. So, you’d be running into a case where your code is more aesthetically pleasing to you, but the visitor would experience longer load times. In this case, a good balance is required. Descendant selecting li’s in a ul is natural, but if you’re applying a style to a semantically unrelated tag, you’ll want to really consider giving it a class… especially if it’s only a few items and the class styles will get reused in other areas of the site. Also, descendant selectors can be more difficult to discern at a glance than a universal class.

    The rest is a good basic tut on web coding.

  9. Amber says:

    @Isaac You’re right about the clearing floats, we just weren’t able to fit everything in. This post was more catered to the n00b developers who overused divs (I used to wrap everything in a container myself) .

    Are you sure it takes longer to parse selectors? I don’t understand why it would take longer versus a class or id.

    Of course if you have multiple similar items, you should use a class versus a selector. These were just some tips as an alternative to classing everything.

    Thanks for the feedback :)

  10. @Isaac I hear what you’re saying about descendant selectors but it is a discussion I didn’t feel necessary to go into in such a tutorial. Like Amber said, it wasn’t possible to fit everything in.

    Hopefully, this article http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/, by Steve Souders – the author of the yslow Firefox plug-in – is the kind of article you had in mind.

    To summarize, the article proves that yes descendant selectors do take slightly longer to render. However, Steve concludes that the performance improvements of classes over descendants are marginal in trivial areas of the website. He does, however, emphasize that there are some CSS rules and interactions with JavaScript which do have a significant effect on performance.

    Given that Steve is somewhat of an authority on website performance and that he has presented his findings with evidence, I feel sufficiently justified to believe him.

    Something else that may be worth mentioning, now that we have deviated from the article a little, is that the use of descendant selectors would immediately be sidestepped if convention dictated it. In fact if the CSS code were to be printed or otherwise displayed separately from the html then it would be far clearer to assign an id to items such as the navigation. Unless of course the code was properly grouped and commented as Amber shows in this blog post: http://www.amberweinberg.com/blog/2009/09/17/clean-css-is-environmentally-friendly/

Leave a Reply