Home > Web Front-end > CSS Tutorial > How Does the DOCTYPE Declaration Affect CSS Height Percentage Calculations?

How Does the DOCTYPE Declaration Affect CSS Height Percentage Calculations?

Barbara Streisand
Release: 2024-12-20 10:24:17
Original
660 people have browsed it

How Does the DOCTYPE Declaration Affect CSS Height Percentage Calculations?

CSS Height Property, Percentage Values, and DOCTYPE

When you specify a height of 100% to your div element, it may not fill the entire page because in standards mode (when the DOCTYPE is included), the browser applies the percentage height relative to the parent element's height. However, if you remove the DOCTYPE, the browser switches to quirks mode and interprets the 100% height relative to the viewport.

Making the Div Fill the Page

To ensure that your div fills the page without removing the DOCTYPE, declare a height on the root element:

html { height: 100%; }
Copy after login

Why Removing the DOCTYPE Affects Height Calculation

When the DOCTYPE is removed, the browser switches from standards mode to quirks mode. In quirks mode, percentage heights of child elements are calculated differently:

  • Standards mode: If the parent element has a height of auto, percentage heights of child elements are also treated as auto.
  • Quirks mode: If the parent element has a height of auto, percentage heights of child elements are measured relative to the viewport.

Since you have not set a height on your div's parent element, the 100% height is measured relative to the viewport in quirks mode, causing the green background to fill the page as expected.

Importance of a DOCTYPE

Using a DOCTYPE is crucial because it ensures that the browser renders your web page in standards mode. This mode follows modern web standards, guaranteeing consistent and reliable rendering across different browsers. Quirks mode, on the other hand, simulates older browsers to accommodate legacy web pages, which can lead to unpredictable and undesired behavior.

Recommended DOCTYPE

For HTML5 documents, the recommended DOCTYPE is simply:

<!DOCTYPE html>
Copy after login

The above is the detailed content of How Does the DOCTYPE Declaration Affect CSS Height Percentage Calculations?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template