我们经常看到下面这样的<!DOCTYPE ...>
:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
!DOCTYPE
的功能是什么?
它告诉验证器你使用的是哪个版本的HTML。浏览器使用这些信息来正确地渲染页面。
以下是正确的DOCTYPE版本:
HTML 4.01 Strict, Transitional, Frameset
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
XHTML 1.0 Strict, Transitional, Frameset
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
XHTML 1.1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
HTML5
<!DOCTYPE html>
主要是为了兼容性。
现代浏览器不再需要它。请参见没有! DOCTYPE的HTML文件:
<p>hello</p>
div {
width:50%;
background-color:#00ff00;
}
<div>div</div>
div {
width:50%;
background-color:#00ff00;
}
<!DOCTYPE html>
<div></div>
<div>some text</div>
<style type="text/css">
div {
background-color:#00ffff;
height:10%;
width:10%;
}
</style>
过去,!DOCTYPE并不是那么简单。你必须指定一个DTD URL:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
DTD 大致如下:
<!ENTITY % HTML.Version "-//W3C//DTD HTML YOURVERSION Transitional//EN"
-- this is a comment.
-->
<!ENTITY % HTML.Frameset "IGNORE">
<!ENTITY % ContentType "CDATA"
-- media type, as per [RFC2045]
-->
<!ENTITY % ContentTypes "CDATA"
-- comma-separated list of media types, as per [RFC2045]
-->
<!ENTITY % Charset "CDATA"
-- a character encoding, as per [RFC2045]
-->
<!ENTITY % Charsets "CDATA"
-- a space-separated list of character encodings, as per [RFC2045]
-->
<!ENTITY % LanguageCode "NAME"
-- a language code, as per [RFC1766]
-->
<!ENTITY % Character "CDATA"
-- a single character from [ISO10646]
-->
<!ENTITY % LinkTypes "CDATA"
-- space-separated list of link types
-->
<!ENTITY % MediaDesc "CDATA"
-- single or comma-separated list of media descriptors
-->
<!ENTITY % URI "CDATA"
-- a Uniform Resource Identifier,
see [URI]
-->
<!ENTITY % Datetime "CDATA" -- date and time information. ISO date format -->
<!ENTITY % Script "CDATA" -- script expression -->
等等,诸如此类。
它告诉您的浏览器正在加载哪个版本的HTML,使加载时间更快,因为浏览器知道可以期望什么。
doctype是由w3c定义的标准 - 当您听到基于标准的Web开发时,这就是他们所谈论的内容。使用doctype的想法是创建遵循doctype的有效HTML。
如果您聪明的话,实际上可以编写自己的doctype。