Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are end tags sometimes required and sometimes not?

Tags:

html

tags

end-tag

Why do 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.

like image 937
ericsoco Avatar asked Jun 13 '11 01:06

ericsoco


Video Answer


2 Answers

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/

like image 71
Swift Avatar answered Nov 15 '22 19:11

Swift


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?

like image 41
Newtang Avatar answered Nov 15 '22 17:11

Newtang