Question

(Everything is tested in the latest firefox.)

This html-code creates an almost screen-filling red box:

<html>
<head>
</head>
<body>
  <div style="height:100%;background-color:red;"></div>
</body>
</html>

But adding a doctype declaration disables relative heights and makes the div's height zero:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div style="height:100%;background-color:red;"></div>
</body>
</html>

Why is this? In particular, I don't get why browsers consider relative heights in a document without doctype, since they don't in explicit html ones.

Was it helpful?

Solution

A doctype enforces a certain set of standards for the browser. If a page does not include a doctype, browsers will usually use some kind of quirks or transitional mode, which is more lenient about markup mistakes (but is bad practice and may display items incorrectly).

Essentially, strictly speaking, you can't set that element to height 100% using that browser's set of standards. It'll try to predict what you wanted to do if you don't include a doctype or include a transitional one and adjust the page's styling accordingly.

OTHER TIPS

You can do it this way: http://cdpn.io/aHlCd

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<style media="all">

html, body {height: 100%; margin: 0; padding: 0;}
div {min-height: 100%; background: red;}

</style>

</head>
<body>

<div></div>

</body>
</html>

You can also just set height on the div rather than min-height.

The above is the answer to why, if you were looking for a fix, setting the position to absolute and applying top,right,left and bottom should do the trick:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div style="position: absolute;height:100%;background-color:red;bottom: 0;top: 0;right: 0;left: 0"></div>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top