Full answer
The <!DOCTYPE html> line at the very top of a page tells the browser to render it in standards mode, which means it follows the current HTML and CSS rules. It is not an HTML tag. It is an instruction, and in HTML5 it is short and case-insensitive.
If it is missing, or is wrong, the browser falls back to quirks mode. Quirks mode exists so that very old pages, written before standards were followed, keep looking the way they did. It changes details of layout, such as how percentage heights, image gaps and table text sizes are worked out. New pages should never depend on it.
You can see the mode from JavaScript: document.compatMode is "CSS1Compat" in standards mode and "BackCompat" in quirks mode.
This page prints CSS1Compat. The next one has the doctype line removed and prints BackCompat:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Quirks mode</title>
</head>
<body>
<p id="mode"></p>
<script>document.getElementById("mode").textContent = document.compatMode;</script>
</body>
</html>An old doctype with a long public identifier, such as the HTML 4.01 Transitional one, can trigger a third mode called limited-quirks (or almost standards) mode, where only a few table-image rules differ. Writing <!DOCTYPE html> avoids all of that. Also put it first: any text before it can push some browsers into quirks mode.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Standards mode</title>
</head>
<body>
<p id="mode"></p>
<script>document.getElementById("mode").textContent = document.compatMode;</script>
</body>
</html>This is a complete page. Removing the first line gives the quirks-mode page shown in the answer, which reports BackCompat.
Key points
- <!DOCTYPE html> is an instruction, not an element, and is case-insensitive.
- A missing or wrong doctype puts the page in quirks mode.
- Quirks mode changes details such as percentage heights, image gaps and table text sizes.
- document.compatMode shows the current mode.
- The doctype must be the first thing in the document.
Common mistakes
- a stray character, comment or BOM-less encoding problem before the doctype, which makes the browser ignore it.
- believing the doctype chooses an HTML version. In HTML5 it only turns on standards mode, and the browser always parses with the current HTML parser.
Follow-ups
- how do you check the mode in DevTools?
- What is limited-quirks mode?
- Why can a stray character before the doctype cause trouble?
Tips
- Always use <!DOCTYPE html> as the first line, followed by <html lang>, a meta charset and a title. Validators and linters expect that pattern.
- A one-line answer is enough: standards mode versus quirks mode, and the check with compatMode.
- Add that the HTML5 doctype is short because it no longer refers to a DTD.