<!DOCTYPE HTML> <html> <body style="height: 100%; padding: 0; margin: 0;"> <div style="background-color: green; height: 100%; width: 100%"></div> </body> </html>
没有什么出现但是如果我删除第一行(doctype),所有页面都是预期的绿色。
我有两个问题:
解决方法
问题的第一部分,询问如何将100%的高度应用于您的div已被其他人多次回答。基本上,在根元素上声明一个高度:
html { height: 100%; }
可以在这里找到完整的解释:
> Working with the CSS height
property and percentage values。
你的问题的第二部分受到的关注较少。我会尽力回答。
Why does removing the
doctype
make [the green background] work?
当您删除DOCTYPE(document type declaration)时,浏览器将从标准模式切换到怪异模式。
在quirks mode,也被称为compatibility mode,浏览器模拟一个旧的浏览器,所以它可以解析旧的网页 – 网页标准出现之前创作的网页。一个浏览器的怪癖模式假装是IE4,IE5 and Navigator 4,所以它可以渲染作为意图的旧代码。
以下是Wikipedia定义怪癖模式的方式:
In computing,quirks mode refers to a technique used by some web
browsers for the sake of maintaining backward compatibility with web
pages designed for older browsers,instead of strictly complying with
W3C and IETF standards in standards mode.
这是MDN的采取:
In the old days of the web,pages were typically written in two
versions: One for Netscape Navigator,and one for Microsoft Internet
Explorer. When the web standards were made at W3C,browsers could not
just start using them,as doing so would break most existing sites on
the web. Browsers therefore introduced two modes to treat new
standards compliant sites differently from old legacy sites.
现在,这里的具体原因为什么高度:100%在您的代码工作在怪癖模式,但不是标准模式:
在standards mode中,如果父元素的高度为:auto(没有定义高度),则子元素的百分比高度也将被视为height:auto(as per the spec)。
这就是为什么第一个问题的答案是html {height:100%; }。
对于高度:100%在div中工作,您必须在父元素上设置高度(more details)。
但是,在怪异模式下,如果父元素的height为auto,则相对于视口测量子元素的百分比高度。
以下是涵盖此行为的三个参考资料:
> https://www.cs.tut.fi/~jkorpela/quirks-mode.html
> http://stackoverflow.com/a/1966377/3597276
> https://developer.mozilla.org/en-US/docs/Mozilla_Quirks_Mode_Behavior
TL; DR
开发人员需要知道的是:
A browser in quirks mode will render web pages in a way that is
unpredictable,unreliable and often undesirable. So always include a
DOCTYPE for the document to render in 07008.Selecting the right DOCTYPE used to be an ambiguous and somewhat
confusing process with 070015. But
today the process is as simple as ever. Just use:06001