Always declare the character encoding

You should always explicitly declare the character encoding of your HTML documents. If you don’t, you might witness unexpected behaviour.

This is the bare minimum I would use for a valid document:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Document</title>
  </head>
  <body>
    <h1>Document</h1>
  </body>
</html>

Running it through the W3C Markup Validation Service, we can see that it’s fully valid HTML with no errors or warnings:

A screenshot showing that the markup is fully valid.

If you don’t include the <meta charset="utf-8"> element, the Web Console in Firefox will show an error:

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.

It’s still “valid” HTML if you omit it, but why make your page more fragile?

The MDN Web Docs explain the charset attribute:

This attribute declares the document’s character encoding. If the attribute is present, its value must be an ASCII case-insensitive match for the string “utf-8”.

If you’re also using non-ASCII characters in your CSS, it’s worth adding the @charset at-rule to the top of your stylesheet as well:

@charset "utf-8";

The MDN Web Docs explain that this is useful when using non-ASCII characters in some CSS properties, like content.


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!