html convention - self-close tag, > or />, in other way <br> or <br/>

谁说我不能喝 提交于 2019-12-10 12:37:19

问题


When take some tutorial from web, I see many people leaves tags open like <link ..>, <img ..>. But when I use Netbeans to edit them (the HTML/JSP pages), it show a red background on those tags until I add the slash into them. <br> --> <br/>.

Which is the correct way to write HTML-based code?


回答1:


Both are fine for HTML. Though not for XHTML which is an XML dialect.

Some elements do not need a closing (/>) tag - in particular empty elements (those that do not have content). Examples are <hr> and <br>. These can also be self closing (<hr /> and <br />, respectively). This self closing is equivalent to having a close tag immediately after the open tag.

For XML, such a non closing tag is not valid - it must be closed, either self closing or have a closing tag. So <hr> is not valid XML, but <hr /> and <hr></hr> are.

HTML is not XML, but for better compatibility some tools try to emit as much XML like HTML as possible.




回答2:


It depends which DOCTYPE you're using. If you're using HTML 4 then you shouldn't use self-closing tags, if XHTML then you should to make valid XML, and if HTML 5 then closing slashes are optional, but not required.

The W3C HTML Validator will throw a warning if you try to use closing tags in HTML 4:

The sequence can be interpreted in at least two different ways, depending on the DOCTYPE of the document. For HTML 4.01 Strict, the '/' terminates the tag '). However, since many browsers don't interpret it this way, even in the presence of an HTML 4.01 Strict DOCTYPE, it is best to avoid it completely in pure HTML documents and reserve its use solely for those written in XHTML.




回答3:


> is correct for HTML, but incorrect for XHTML. Check your DOCTYPE.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

for HTML strict and

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

for XHTML strict



来源:https://stackoverflow.com/questions/6079746/html-convention-self-close-tag-or-in-other-way-br-or-br

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!