HTML best practices help developers offer innovative and highly interactive websites and web apps. These best practices help you develop the most feature-rich and business-centric applications. Plus, organizations can harness these best practices to provide a seamless user experience.

Today, when we talk about HTML, we typically discuss HTML5 (and not its immediate predecessors). HTML5 is a powerful markup language that allows web developers to create a web document. It’s easy to use and understand, and almost all browsers support it. Also, it’s the foundation of almost all Content Management Systems (CMS)

As a web developer with minimal experience, questions such as “How can I write better HTML?” often arise. This article aims to help you get started on the right foot.

General HTML Coding Approach

You probably already have a grasp of this markup language, but here are some HTML5 best practices that will let you code better.

Always Declare a Doctype

When creating an HTML document, the DOCTYPE declaration is required for informing the browser what standards you’re using. Its purpose is to render your markup correctly.

For example:

Version Doctype Declaration
HTML 4.01 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
XHTML 1.1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
HTML5 <!DOCTYPE html>

The <DOCTYPE> declaration should be in the first line of your HTML document. Here is a comparison between its right and wrong implementation:

Best Practice Bad Practice
<!DOCTYPE html>
<html>...</html>
<html>...</html>

Alternatively, you can use the doctype corresponding to the HTML/XHTML version you want to use. Learn about the recommended list of doctype declarations to help you choose the right one.

HTML Tags Placement

Developers know that the purpose of tags is to help web browsers distinguish between HTML content and ordinary content. HTML tags contain an opening tag, content, and closing tag. However, they’re often confused about the proper placement of tags, the elements that require closing tags, or when to omit tags.

For instance, where’s the best place to put <script> tags?

Script tags are typically placed inside the <head> element. But a modern HTML best practice is to place them at the bottom of the document instead, before closing the <body> tag, to delay their download. The webpage will load the Document Object Model (DOM) first, show it to the user, and then request the scripts afterward, reducing time to first byte (TTFB).

The browser interprets your HTML document line by line from top to bottom. So, when it reads the head and comes across a script tag, it starts a request to the server to get the file. There’s nothing inherently wrong with this process, but if the page is loading a huge file, it will take a long time and greatly affect the user experience.

The Root Element

Under the root element is the <lang>, or language, attribute. This attribute helps in translating an HTML document into the proper language. The best practice is to keep this attribute’s value as short as possible.

For example, the Japanese language is mostly used in Japan. Therefore, the country code is not necessary when targeting the Japanese language.

Best Practice Bad Practice
<html lang="ja"> <html lang="ja-JP">

Do’s and Don’ts in HTML

One of the most common HTML best practices is to check on the do’s and don’ts. Here are some known don’ts in HTML coding:

Description Good Practice Bad Practice
In the text, use Unicode characters’ HTML code equivalent instead of the character itself. <p>Copyright © 2021 W3C<sup>®</sup></p> <p>Copyright © 2021 W3C<sup>®</sup></p>
Eliminate white spaces around tags and attribute values. <h1 class="title">HTML5 Best Practices</h1> <h1 class=" title " > HTML5 Best Practices </h1>
Practice consistency and avoid mixing character cases. <a href="#status">Status</a> <a HREF="#status">Status</a>
Don’t separate attributes with two or more white spaces. <input type="text" name="LastName"> <input type="text" name="LastName">

Keep It Simple

Like any coding practice, the “keep it simple” principle is very applicable to HTML and HTML5. Generally, HTML5 is compatible with older HTML versions and XHTML. For that reason, we recommend avoiding the use of XML declarations or attributes.

For example:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE html>

You don’t need to declare code as such unless you want to write an XHTML document. Similarly, you don’t need XML attributes, such as:

<p lang="en" xml:lang="en">...</p> 

Code With SEO in Mind

Developers should code with SEO in mind. Web contents that are not found are also not indexed. For that reason, here are some best SEO best practices to consider:

Add Meaningful Metadata

The <base> tag is a handy tag, but misusing it may result in some non-intuitive behaviors. Thus, if you declare a base tag, then every link in the document will be relative unless explicitly specified:

<base href="http://www.kinsta.com/" />

This syntax changes the default behavior of some links. For example, linking to an external webpage with only the page name and extension:

href="coding.org"

Or the browser will interpret it as:

href="http://www.kinsta.com/coding.org"

This interpretation becomes chaotic, so it’s safer to always use absolute paths for your links.

On the other hand, writing metatag descriptions is not strictly a part of HTML best practices, but it’s still equally important. The <meta name="description"> attribute is what search engine crawlers reference when they index your page, so it’s vital to your SEO health.

Set Appropriate Title Tags

The <title> tag makes a web page search engine-friendly. For one thing, the text inside the <title> tag appears in Google’s Search Engine Result Pages (SERP) and the user’s web browser bar and tabs.

Take, for example, when you search the keyword “HTML5.” The title in this search result indicates the specific title attribute and the author. This is very important in SEO and site traffic generation.

Images Must Have an Alt Attribute

Using a meaningful alt attribute with <img> elements is a must for writing valid and semantic code.

In the table below, the bad practice column shows an <img> element without an alt attribute. Although the second example in the same column has an alt attribute, its value is meaningless.

Good Practice Bad Practice
<img id="logo" src="images/kinsta_logo.png" alt="Kinsta logo" />
<img id="logo" src="images/kinsta_logo.png" />
<img id="logo" src="images/kinsta_logo.png" alt="kinsta_logo.png" />

Descriptive Meta Attributes

The meta description is an HTML element that describes and summarizes the contents of a webpage. Its purpose is for the users to find the context of the page. Although metadata doesn’t help anymore with SEO rankings, the meta description still plays a significant role in on-page SEO.

Here is a sample code that includes the keywords, description, author’s name, and character set. The character set is used to support almost all the characters and symbols from different languages. On the other hand, you can set cookies, add a revision date, and allow the page to refresh.

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Best Practices in Website Design</title>
    <meta name = "keywords" content = "HTML, Website Design, HTML Best Practices" />
    <meta name = "description" content = "Learn about HTML best practices." />
    <meta name = "author" content = "John Doe" />
    <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8" />
  </head>
  <body>
    <p>Let's learn how to code HTML5!</p>
  </body>
</html>

Title Attribute With Links

In the anchor elements, the best practice is to use title attributes to improve accessibility. The title attribute increases the meaning of the anchor tag. The <a> tag (or anchor element) paired with its href attribute, creates a hyperlink to web pages, email addresses, and files. It is used to link locations within the same page or external addresses.

Check the example under the bad practice column — it’s there for being redundant. This type of practice is evident if a user uses a screen reader to read the anchor tag and read the same text twice to the listener. A screen reader is an assistive technology provided to the visually impaired or those with a learning disability. As a good practice, if you’re just repeating the anchor’s text, then it’s better not to use a title at all.

Good Practice Bad Practice
<a href="http://kinsta.com/our-pricing" title="Learn about our products.">Click here</a> <a href="http://kinsta.com/our-pricing" title="Click Here">Click here</a>

HTML Best Practices for Layouts

Website development isn’t simply a matter of creating a block of text and headers, link pages, and you’re done. There are some best practices in HTML to consider to make the best of your website.

Set a Proper Document Structure

The HTML documents will still work without the primary elements: <html>, <head>, and <body>. However, pages may not render correctly if these elements are missing. To that end, it’s important to use proper document structure consistently.

Group Relevant Sections

For a thematic grouping of content, use the section element. According to the W3C specification, a <section> should contain a heading (H1, H2, etc.). Some developers skip the use of the heading element entirely, but we recommend including it to reach those better using screen readers:

Good Practice Bad Practice
<section>
<h1>HTML Best Practices 2021</h1>
<ul>
<li><img src="img1.jpg" alt="description"></li>
<li><img src="img2.jpg" alt="description"></li>
</ul>
</section>
<section>
<ul>
<li><img src="img1.jpg" alt="description"></li>
<li><img src="img2.jpg" alt="description"></li>
</ul>
</section>

Embedded Content Best Practices

The <embed> tag serves as a container for an external resource. This includes web pages, pictures, videos, or plug-ins. However, you must consider that most browsers no longer support Java Applets and plug-ins. What’s more, ActiveX controls are no longer supported in any browser, and the support for Shockwave Flash has also been turned off in modern browsers.

We recommend the following:

  • For a picture, use the <img> tag.
  • For HTML pulled in from another site, use the <iframe> tag.
  • For videos or audios, use the <video> and <audio> tags.

The alt attribute in the<img> element provides an image description useful to search engines and screen readers. It can come in especially handy to users when the images can’t be processed:

Good Practice Bad Practice
<img alt="HTML Best Practices" src="/img/logo.png"> <img src="/img/logo.png">

Leave the alt attribute empty if there’s supplemental text to explain the image. This is to avoid redundancy:

Good Practice Bad Practice
<img alt="" src="/img/icon/warning.png"> Warning <img alt="Warning Sign" src="/img/icon/warning.png"> Warning

Leave <iframe> elements empty if there are some restrictions in its content. An empty iframe element is always safe:

Good Practice Bad Practice
<iframe src="/default.html"></iframe>
<iframe src="/default.html">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
</iframe>

Developers should provide fallback content, or backup links, for any <audio> or <video> elements, just as with images. Fallback content is needed, especially for newly introduced elements in HTML:

Good Practice Bad Practice
<video>
<source src="/mov/theme.mp4" type="video/mp4">
<source src="/mov/theme.ogv" type="video/ogg">...<iframe src="//www.youtube.com/embed/..." allowfullscreen></iframe>
</video>
<video>
<source src="/mov/theme.mp4" type="video/mp4">
<source src="/mov/theme.ogv" type="video/ogg">...</video>

Reduce the Number of Elements

HTML documents become complicated, especially for web pages with a lot of content. It’s best to reduce the number of elements on a page to as few as you can manage. Learn how to use the heading elements wisely and follow how <h1> to <h6> elements denote HTML’s content hierarchy. This makes your content more meaningful for your readers, screen-reading software, and search engines.

Example:

<h1>The topmost heading</h1>
<h2>This is a subheading that follows the topmost heading.</h2>
<h3>This is a subheading that follows the h2 heading.</h3>
<h4>This is a subheading that follows the h3 heading.</h4>
<h5>This is a subheading that follows the h4 heading.</h5>
<h6>This is a subheading that follows the h5 heading.</h6>

For WordPress developers and content creators, use the <h1> element for the blog post’s title instead of the site’s name. This helps in search engine crawling, and this approach is SEO-friendly.

In addition, use the right HTML element to convey the information it contains to achieve a semantic and meaningful content structure. For example, use <em> for emphasis and <strong> for heavy emphasis instead of their predecessors <i> or <b>, which are now deprecated.

Example:

<em>emphasized text</em>
<strong>strongly emphasized text</strong>

Just as importantly, use <p> for paragraphs, and avoid using <br /> to add a new line between paragraphs. Instead, make use of CSS margin and/or padding properties to position your content better. Sometimes, you might find yourself tempted to use the <blockquote> tag for indentation purposes. Avoid this pitfall — use it exclusively when quoting text.

Do’s and Dont’s for Layouts

One of the best HTML best practices is to use semantically appropriate elements in your page layout. Several elements will help you organize your layout in sections.

With the wide breadth of topics under HTML layout, it’s best to highlight the do’s and don’ts in layout quickly. For instance, HTML gives more semantic meaning to the header and footer elements, so don’t neglect the use of the <header> tag as it’s used in any given section or article. Aside from controlling the <title> and <meta> tags and other stylistic elements of the document, it’s used in headings, publish dates, and other introductory content of your page or section. Similarly, you can do away with the notion that footers belong to the copyright section only — now, you can use it just about everywhere.

For the <nav> element, you should use it for site-wide navigation. There is no need to declare a role as the usage is already implied in the tag.

Good Practice Bad Practice
<nav></nav> <nav role="navigation"></nav>

As for the <main> element, it is already part of the latest HTML5 versions, which denote the main content of the document body. So, there is no longer any need to use <div> when we have a more specific tag for our main content.

Good Practice Bad Practice
<main id="content"></main> <div id="content"></div>

The <article> is used for a content block. It is a stand-alone and makes sense without the need to give further explanation, while the <section> tag is used to divide a page into different subject areas or to section an individual article. Unfortunately, many developers still use the two interchangeably.

Consider that the <section> tag is a more generic tag than the <article> tag. This means that the former denotes content related to the topic at hand, but not necessarily self-contained. The latter, conversely, is a stand-alone property.

But when there’s no appropriate markup tag for your purposes, what should you use? The answer is to use <div> when no other element works or when it’s a specifically stylistic element. For our purposes, using <div> is also a bad practice.

Let’s go back to the <section> tag, which is a semantic markup tag. It is not a stylistic one, and it is important to emphasize it. In effect, a good coding practice should include a heading tag.

Now, the don’ts with <section> follows that you shouldn’t use it to tag a wrapper, a container, or any other purely stylistic block. Below is an example of bad coding practice with the <section> tag:

<section id="wrapper">
  <section class="container-fluid">
    <div id="main">
    </div>
  </section>
</section>

Here is a better approach, but it overuses the <div> tag:

<div id="wrapper">
  <div class="container-fluid">
    <div id="main">
    </div>
  </div>
</div>

Hence, a much better coding practice is:

<body id="wrapper">
  <div class="container-fluid">
    <main id="main">
    </main>
  </div>
</body>

A popular part of many layouts are figures for data representation, and the <figure> element is mostly used with pictures. However, it has a wider range of possible uses, as anything related to the document could be positioned anywhere and wrapped in a <figure> element. Some examples include illustrations, tables, or diagrams in a book.

An interesting characteristic of <figure> is that it does not contribute to the document’s outline. Therefore, you can use it to group elements with a common theme — for instance, several images with one common <figcaption>, or even a block of code.

In grouping elements with <figure>, use <figcaption>. The <figcaption> caption should go either directly after the opening <figure> tag, or directly before the closing </figure> tag :

<figure>
  <img src="image1.jpg" alt="Bird Image">
  <img src="image2.jpg" alt="Tree Image">
  <img src="image3.jpg" alt="Sun Image">
  <figcaption>Three images related to a topic</figcaption>
</figure>

HTML Best Practices in Scripting

HTML is one of the core technologies in web development. It has awesome power and features that made it popular with developers and business owners. Frontend development keeps on innovating, and to keep up with it, developers should know the best practices in HTML scripting.

Use External Style Sheets

Inline styles will make your code cluttered and unreadable. To that end, always link to and use external stylesheets. Also, avoid using import statements in your CSS files as they produce an extra server request.

The same goes for inline CSS and JavaScript. Apart from readability issues, this will make your document heavier and more difficult to maintain so that you can avoid inlining code.

Use Lowercase Markup

Using lowercase characters in code is an industry-standard practice. Although using uppercase or other text cases will still render your page, the problem is not standardization but code readability.

Code readability is an important aspect of coding as it helps make applications maintainable and secure. Not only that, web development mostly comprises a team. Making your code readable makes your work and the work of your team less complicated.

Good Practice Bad Practice
<div id="test">
<img src="images/sample.jpg" alt="sample" />
<a href="#" title="test">test</a>
<p>some sample text </p>
</div>
<DIV>
<IMG SRC="images/sample.jpg" alt="sample"/>
<A HREF="#" TITLE="TEST">test</A>
<P>some sample text</P>
</DIV>

Do’s and Don’ts in Scripting

While there are many don’ts in coding HTML, we’ll share two basics don’ts in scripting:

  • Write well-indented and consistently formatted codes: Clean and well-written code promotes better readability on your site, which is a huge help to your developer and other people who might work with the site. It also shows great professionalism and attention to detail, reflecting well on your attitude as a developer.
  • Refrain from including excessive comments: Comments are essential and make your code easier to understand. However, HTML syntax is very self-explanatory, so commenting is not necessary unless you have to clarify semantics and naming conventions.

Validating and Minifying

Validating and minifying codes are used to identify errors early on. Don’t wait until you finish your HTML document — make it a habit to validate and identify errors frequently. You can do validation either manually or use any known validator tool such as W3C Markup Validator.

You can also take advantage of the built-in code minification feature in the MyKinsta dashboard. This allows customers to enable automatic CSS and JavaScript minification with a simple click, which will speed up their sites with zero manual effort.

At the same time, practice minification by removing anything that is not essential such as comments or whitespace. Ensure that you write clean and concise codes to reduce the size of your HTML file. You can use tools such as HTML Minifier and others.

Summary

Many HTML5 best practices resources for 2021 are available online to assist you. However, remember the general rule in coding: consistency. This article has provided basic insights and helped you kick-start that frontend development journey. Using this guide, you’ll be an expert in semantically correct HTML5 in no time.

When you’re ready, look beyond what HTML can offer and explore some open source HTML frameworks too for building modern, single-page web apps. They offer excellent synchronization between the data and UI and work seamlessly with CSS and JavaScript.

Did we miss any HTML best practices that you use in your own coding? Let us know in the comments section!

Iryne Vanessa Somera