Best Practices Part 1: HTML

August 17th, 2015

In my daily toil I’ve been spending a lot of time managing a vendor (to remain unnamed) putting together a Magento instance for my company these past few months. I worked closely with them throughout the project, handled all design creation and asset management as well as project requirements and in overall project management. It was a weird but educational experience, and I can honestly say I have more knowledge of Logistics, Accounting and Customer Service than ever before. But the most important thing I learned from this experience was that when someone says “best practices coding” they could very easily have a wildly different interpretation than you.

And so after being delivered code that looked nothing like the “best practices” I was expecting I wrote up an exhaustive list of what I consider the tenets of best practices front end web development to guide our vendor. After rave reviews from everyone who already likes me I’ve decided to share this list with the world. In case anyone else gets fooled by their vendor promising “best practices” and delivering far from.

What are Best Practices?

Websters dictionary defines best practices as…  (this is happening, suck it Mrs. Waldorf from 12th grade English)

a procedure that has been shown by research and experience to produce optimal results and that is established or proposed as a standard suitable for widespread adoption

Which pretty much means a set of conventions and rules that enough people are using and have so much success with that they can be considered a standard in the field.

Why We Use Them

  • They help us work on collaborative projects with multiple designers and developers.
  • They help us build projects that are maintainable and extensible.
  • They help us optimize our work, as the secondary services all our websites must work with (i.e. Google) expect us to be using them.

They’re a good thing. Embrace them. Literally. Print out and hug this guide. No, I’m not kidding.

This guide will assume that you already have a basic understanding of these technologies. That, like me, you know your way around the html block but just need a few pointers on where to plant your flowers (Or something. Analogies are hard). But please keep in mind I can only say these are my opinions based on the experience I’ve gained working professionally in the industry, take it or leave it. Without further ado, lets dive into all the ways you should be coding your HTML.

HTML

HTML has come a long way in it’s lifetime. I remember the days of <blink> and <marquee> and thinking that was the coolest sh*t I’d ever seen. I was wrong, but you get the idea, we’ve learned a lot from our annoyingly flashy days. Today’s HTML follows the HTML5 w3C spec released in 2014. Yes, you should probably read that and no, it will not be fun. But, when you’re done and you still want to feel really bad about your code the w3c provides this handy-dandy validator that will crawl whatever site you submit and tell you all the ways you screwed it up. When you’re done crying come on back and lets get down to fixing it.

Know Your DOCTYPE and Charset

The first line of your HTML document should be your DOCTYPE. And thanks to HTML5 you no longer have to use one of these long, ugly strings of slashes.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Thanks to HTML5 we now get a much smaller sleeker DOCTYPE declaration.

<!DOCTYPE html>

Same with our character encoding declaration. All of this jibber jabber…

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Can be replaced by this short and sweet version.

<meta charset="utf-8">

The basic principle to keep in mind when coding HTML is that it is not intended to define the look and feel of the content on the page beyond simple concepts like headers, paragraphs and lists. What does this mean?

Tables Should Never be Used for Page Layout

Except in the case of HTML email: if it’s not a table, don’t use a table. Tables should be used to display tabular data ONLY. When doing so you should use THEAD, TH tags (with scope attributes), and TBODY tags.

<table summary="This is a summary of your rad table contents.">
	<thead>
		<tr>
			<th scope="col">Table Header 1</th>
			<th scope="col">Table Header 2</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>Table Data 1</td>
			<td>Table Data 2</td>
		</tr>
	</tbody>
</table>

Lists Should Never be Used for Page Layout

If it’s not a list, don’t use a list. This can sometimes be a judgment call, just ask yourself, “Am I using this element as a list?”. A Navigation with a list of links? Use a list. A set of 3 divs on your homepage? Don’t use a list. Simple as that.

When you need to use a list all items in list format should always be wrapped in a UL, OL or DL.

Write Page Layout Markup that Represents the Semantics of the Content of the Document

The new HTML5 spec came loaded with some extremely useful semantic elements.

  • <header> – defines a header segment site-wide or within another element
  • <footer> – defines a footer segment site-wide or within another element
  • <section> – a thematic grouping of content
  • <article> – independent, self-contained content (i.e. blog posts, articles, comments) content that can be independently distributed or reused
  • <nav> – defines a section with navigation links to navigate to other pages or within the same page
  • <aside> – defines content relative to it’s neighboring content (think: sidebar)
  • <blockquote> – defines a section quoted from another source (with cite attribute)
  • <figure> – self-contained (but not wholly independent) content like illustrations, diagrams, photos etc
  • <figcaption> – captions of figure elements

Boom! Look at that arsenal of elements! Think of the all the combinations your element soup can give you now. Like so:

<header>
	<h1>Semantic HTML LIKEABOSS</h1>
</header>
<nav>
	<ul>
		<li>Navigation Link 1</li>
		<li>Navigation Link 2</li>
		<li>Navigation Link 3</li>
	</ul>
</nav>
<section>
	<article>
		<header>
			<h1>Super Cool Article Title</h1>
		</header>
		<section>
			Article content Uno.
		</section>
	</article>
	<article>
		<header>
			<h1>Another Article Title</h1>
		</header>
		<section>
			Article content dos!
		</section>
	</article>
</section>
<aside>
	<section>
		<h1>Other Super Cool Sites</h1>
		<ul>
			<li>Link</li>
			<li>Link</li>
			<li>Link</li>
		</ul>
	</section>
	<figure>
		<img alt="Your super cool sidebar image." src="https://i.imgur.com/ab97qhn.jpg">
		<figcaption>Pizza is bae.</figcaption>
	</figure>
</aside>
<footer>
	Copyright 2015
</footer>

Mmm look at that semantic sexiness. So clean, so light, so search engine friendly.

Make sure you’re using the old elements in their correct fashion as well. Use <p> elements for individual paragraphs instead of one long paragraph element with <br /> tags to delineate line breaks.

<p>
	Paragraph one sits in a separate element.
</p>
<p>
	And paragraph two sits in yet another element.
</p>

Utilize Microformats/Microdata

Microformats are how we can make contact information on our page machine readable.

<ul class="vcard">
	<li class="fn">The Muffin Man</li>
	<li class="org">Muffin Man, Inc.</li>
	<li class="tel">714-867-5309</li>
	<li>http://www.muffinman.com/</li>
</ul>

Using the class “vcard” indicates to the browser that the other classes form an hCard (HTML vCard) and have relevant class names. Another such example are geographic coordinates.

<div class="geo">
	<p class="latitude">52.48</p>
	<p class="longitude">-1.89</p>
</div>

All these fancy new features do require the support of HTML5. And as well all know Internet Explorer sucks, specifically the supporting of it and its antiquated versions that an unfortunate amount of people still use. For Internet Explorer 9 and below I highly recommend the use of the HTML5Shiv by Alexander Farkas. That way you can keep using all these fancy new elements without having to worry about gross old legacy Internet Explorer.

Don’t Forget Form Labels

Use label fields on all form fields. Use the ‘for’ attribute to associate each label with the relevant input. Even if the design doesn’t call for labels they should still be placed in HTML markup and hidden with CSS to allow screen readers to interact with the form.

<label for="username">Username</label>
<input id="username" type="text">

New input types like “email” and “url” are now available to you and provide some real-time browser validation. You can use the placeholder attribute to provide input hints and the boolean required attribute to require the field. All rolled into one:

<form>
	<label for="email">Email:</label>
	<input id="email" type="email" placeholder="Your Email" required>
</form>

Lastly do not use size attribute on input fields, which is relative to the font-size of the text inside the input. Use CSS width instead.

Keep Your Content Legible To Humans and Others

Always use title-case for headers and titles. Do not write all capital letters or all lowercase in markup. Apply these case changes through CSS text-transform. I would not want my website shouting at a visually impaired person utilizing a screen reading service. (I have no actual confirmation that this would be the case but if there’s even the slight chance it could be I’d rather avoid it.)

<style>
	h1 {
		text-transform: uppercase;
	}
</style>
<h1>Al Harrington's Wacky Waving Inflatable Arm-Flailing Tubeman Emporium and Warehouse</h1>

All images need alt tags with a short description of the images contents for both accessibility and search rank.

<img src="https://i.imgur.com/s7B1H9F.jpg" alt="Cheers!">

WYSIWYG editors notoriously handle white-space poorly. Set the ‘white-space’ property on markup generated from them to the value ‘pre-wrap’.

And Always Be Polite

Place HTML comments on closing div tags to indicate what element you’re closing. Intricate projects can have extensive nesting and indentation, as well as complex file structures that could place the open half of your element in a completely separate file. Keeping these little cues will help all hands involved.

<section class="main column">
	<div class="content-inner">
		<p>Content...</p>
		<p>Content...</p>
		<p>Content...</p>
	</div> 
</section> 

Wrapping Up

Well that’s all for the HTML portion of this presentation. I’m sure there are some best practices rules I may have missed or some principles I’ve glossed over. Feel free to add them in a comment below! Join us next time for the most stylish language of front end development, CSS (zing! Sorry not sorry).

2 Comments


  1. Ben

    “Place HTML comments on closing div tags to indicate what element you’re closing.”

    In my opinion this is not a good idea. Most text editors support collapsing of tags and extra unnecessary markup just makes it tedious to make changes. Then theres the problem of someone editing a class name in the file, but then forgetting to update the closing tag which is then out of date and could lead to further errors when editing.

  2. Great post, really informative and easy to read! I was aware of some of these changes, but definitely learned some new stuff such as the email and url form labels with validation. Dope stuff, thanks for the read! bookmarked

Comment