What is Doctype in HTML: Definition and Usage
DOCTYPE in HTML is a declaration that tells the web browser which version of HTML the page uses. It helps the browser display the page correctly by setting the rendering mode.How It Works
The DOCTYPE declaration is like a sign at the entrance of a building telling visitors what rules to follow inside. For web browsers, it signals which version of HTML the page is written in. This helps the browser understand how to read and display the content properly.
Without this declaration, browsers might guess the HTML version and show the page in a "quirks mode," which can cause layout and style problems. By specifying the DOCTYPE, you ensure consistent and predictable rendering across different browsers.
Example
This example shows the simplest and most common DOCTYPE declaration for modern HTML5 pages.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Doctype Example</title> </head> <body> <h1>Hello, world!</h1> <p>This page uses the HTML5 doctype.</p> </body> </html>
When to Use
You should always include the DOCTYPE declaration at the very top of every HTML document. It is essential for:
- Ensuring browsers render your page in standards mode, avoiding quirks mode.
- Helping tools and validators understand your HTML version.
- Improving cross-browser compatibility and consistent layout.
In modern web development, use the simple HTML5 <!DOCTYPE html> declaration for all new projects.
Key Points
- DOCTYPE tells the browser which HTML version to use.
- It must be the very first line in an HTML file.
- Using the correct doctype prevents layout issues.
- HTML5 uses a simple and short doctype:
<!DOCTYPE html>.