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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With