Why does height 100% work without DOCTYPE declaration?
P粉818561682
P粉818561682 2023-10-26 10:39:42
1
2
672

This is the complete code:

<!DOCTYPE HTML>
<html>
<body style="height: 100%; padding: 0; margin: 0;">
    <div style="background-color: green; height: 100%; width: 100%"></div>
</body>
</html>

Nothing appears. However, if I remove the first line (doctype), all pages turn green as expected.

I have two questions:

  1. How to make div fill the page without removing the markup?
  2. Why does it work normally if I delete doctype?


P粉818561682
P粉818561682

reply all(2)
P粉043432210

Do you mean vertical? divs are block-level elements, so by default they fill the parent element horizontally.

In order for this to work, you also need to set the height of the HTML tag to 100%.

html, body { height:100%; }

See a working example here:

http://jsfiddle.net/uhg0y9tm/1/

As some others here have said, once you remove the first line (HTML5 document type), browsers will render the page differently, in which case there is no need to specify an explicit height of 100% for the HTML tag.

P粉904405941

CSS height Properties, percentage values ​​and DOCTYPE

The first part of your question asks how to apply 100% height to your div , which has been answered multiple times by others. Essentially, declare the height of the root element:

html { height: 100%; }

A full explanation can be found here:


The second part of your question has received much less attention. I'll try to answer this question.

When you remove a DOCTYPE (Document Type Declaration), the browser switches from Standard Mode to Weird Mode.

In Weird Mode, also known as Compatibility Mode, the browser emulates old browsers so that it can parse old web pages - pages written before web standards existed. The browser in weird mode will pretend to be IE4, IE5 and Navigator 4 so that it can render old code as the author intended.

Here's how Wikipedia defines quirks mode:

The following is the opinion of MDN:

Now, here are the specific reasons why height: 100% in the code works in weird mode but not in standard mode:

In standards mode , if the parent element has height: auto (no height is defined), then the child element's percentage height will also be treated as height: auto (according to specification).

That's why the answer to your first question is html { height: 100%; }.

To make height: 100% work in a div, you must set height on the parent element (More details).

However, in weird mode, if the parent element has height: auto, the child element's percentage height will be measured relative to the viewport .

The following are three references covering this behavior:


TL;DR

In a nutshell, here’s what developers need to know:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template