HTML

Best practices for HTML.


Table of contents


General

Define important document properties

Good
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>HTML best practices</title>
  </head>
  <body>
    ...
  </body>
</html>
Bad
<html>
  <body>
    ...
  </body>
</html>

Put stylesheets at the top

Ensure that styles are applied as early as possible during page render by placing all stylesheet links in the <head> section.

Good
<html>
  <head>
    <link rel="stylesheet" href="style.css" />
    <style type="text/css"></style>
  </head>
  <body>
    ...
  </body>
</html>
Bad
<html>
  <head>...</head>
  <body>
    ...

    <link rel="stylesheet" href="style.css" />
    <style type="text/css"></style>
  </body>
</html>

Put scripts at the bottom

Prevent content being rendered from being blocked by placing all scripts just before the closing </body> tag.

Good
<html>
  <head>...</head>
  <body>
    ...

    <script type="javascript"></script>
    <script type="javascript"></script>
  </body>
</html>
Bad
<html>
  <head>
    <script type="javascript"></script>
    <script type="javascript"></script>
  </head>
  <body>
    ...
  </body>
</html>

Prefer specific elements to generic elements

Less markup, better readability.

Good
<body>
  <header>...</header>
  <main>
      <article>
          <section>...</section>
      </article>
  </main>
  <footer>...</footer>
</body>
Bad
<body>
  <div class="header">...</div>
  <div class="main">
    <div class="article">
        <div class="section">...</div>
    </div>
  </div>
  <div class="footer">...</div>
</body>

Omit value for boolean attributes

Values for boolean attributes are obsolete and should be omitted.

Good
<input type="radio" checked />

<input type="text" disabled />
Bad
<input type="radio" checked="checked" />

<input type="text" disabled="disabled" />

Images

Good
<img src="white_horse.png" width="120" height="90" alt="White Horse" />
Bad
<img src="white_horse.png" />