且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

忽略< html>的缺点是什么?和< body>

更新时间:2022-11-30 12:10:57

在规范中是可选的(所以文档仍然有效)。

OO 含义开始标记可选,结束标记可选)到当前规范(其中写有如果html元素中的第一个元素不是一个html元素的结束标签可以省略,如果html元素后面没有注释。)。



它们只是必填项XHTML自XML以来没有可选标签的概念。



我从来没有见过任何浏览器或用户代理无法在HTML文档中正确处理它们。 (请注意,虽然标记是可选的,但是元素不是,所以即使标记缺失,浏览器也会插入HTML,HEAD和BODY元素,因此任何试图在DOM中查找它们的脚本仍然可以工作) p>

唯一的技术缺点是不能将属性放在那些不存在的标签上,而且 lang 属性因为HTML元素是很有用的。



将它们排除在外可能会让其他需要维护代码但不知道标记是可选的代码的人混淆。


Is there any drawback to never using

<html> and <body>

on your web pages that are written in HTML and PHP? I mean, everything works perfectly fine with it or without it, so why use it?

They are explicitly optional in the spec (so the document will still be valid).

This has been true since the original spec (which says <!ELEMENT HTML O O (( HEAD | BODY | %oldstyle)*, PLAINTEXT?)>, O O meaning Start Tag Optional, End Tag Optional) through to the current spec (which says "An html element's start tag can be omitted if the first thing inside the html element is not a comment. An html element's end tag can be omitted if the html element is not immediately followed by a comment.").

They are only mandatory in XHTML since XML has no concept of optional tags.

I've never seen any browser or user-agent fail to handle them correctly in an HTML document. (Note that while the tags are optional, the elements are not, so browsers will insert an HTML, HEAD and BODY elements even if the tags are missing, so any script which tries to find them in the DOM will still work).

The only technical drawback is that you can't put attributes on tags which aren't there, and a lang attribute for the HTML element is useful.

Leaving them out can confuse other people who have to maintain your code who don't know that the tags are optional though.