开发者

Why are end tags sometimes required and sometimes not?

Why do 开发者_JS百科some html opening/start tags require a closing/end tag?

for example, <script> requires a </script>, while <img> can (in fact, must) be self-closing (<img src="path.jpg" />)?

I would assume it has to do with requiring content between start and end tags, but with the example of <script>, <script src="file.js"></script> doesn't need anything in between...

I ask because I burned time trying to figure out why my included script was working in Safari but not in FF or Chrome. it was because I incorrectly self-closed the script tag. bleh.


The reason for the existence of self closing tags is that certain elements naturally will never have content that goes between the tags. For instance, think about the <br / tag. When would something like <br></br> be useful? It's really just a waste of character space and time. This syntax stems from the XML syntax and became part of XHTML.

Determining which tags can/should be self closing is up the HTML parser in the browser. The HTML specification for the version you're using should define the way things are handled, but of course we all know that it never necessarily the case.

Here is a great article about self closing tags in HTML5 (& past versions) for your reference.

http://tiffanybbrown.com/2011/03/23/html5-does-not-allow-self-closing-tags/


It's actually valid HTML4 and HTML5 to omit a wide variety of end tags (but not XHTML). Here's a whole list: http://www.w3.org/TR/html5/syntax.html#optional-tags

In addition there's several void elements that simply can't have any content (like img). Here's a list of those: http://www.w3.org/TR/html5/syntax.html#void-elements

As for script tags, there's a good Stack Overflow discussion about this: Why don't self-closing script tags work?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜