Home >Web Front-end >CSS Tutorial >Why does a 100% height div only fill the page when the DOCTYPE is removed?

Why does a 100% height div only fill the page when the DOCTYPE is removed?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 13:37:11440browse

Why does a 100% height div only fill the page when the DOCTYPE is removed?

Why does height 100% work when DOCTYPE is removed?

This code snippet attempts to fill the entire page with a green div:

<!DOCTYPE HTML>
<html>
<body>

However, it doesn't work as expected. The div remains invisible. If we remove the DOCTYPE declaration (), the div suddenly expands to fill the entire page. This raises two questions:

How do I make the div fill the page without removing the DOCTYPE declaration?

To make the div fill the page without removing the DOCTYPE, simply set the height of the root element (html) to 100%:

html { height: 100%; }

Why does removing the DOCTYPE declaration make it work?

When a DOCTYPE is present, the browser renders the page in standards mode. In standards mode, percentage heights of child elements are treated as height: auto if the parent element has no explicit height. This is why the div doesn't fill the page in standards mode.

However, when the DOCTYPE is absent, the browser switches to quirks mode. In quirks mode, percentage heights of child elements are measured relative to the viewport. This means that the div in the example above will fill the entire page in quirks mode because its height is set to 100% of the viewport height.

Conclusion

It's important to always include a DOCTYPE declaration to ensure that the page renders in standards mode. Quirks mode is unreliable and unpredictable, and it should be avoided at all costs. The preferred DOCTYPE declaration is simply:

<!DOCTYPE html>

The above is the detailed content of Why does a 100% height div only fill the page when the DOCTYPE is removed?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn