Closing HTML tag

落花浮王杯 提交于 2020-06-25 03:36:11

问题


When is it appropriate to use a closing tag and when a slash is enough?

<div></div>

vs.

<div />

回答1:


You can only use a self closing tag <div /> if your DOCTYPE is set to XHTML as this is borrowed from XML where you can have self closing tags. You can't have it if your DOCTYPE is set to HTML 4.01 or HTML 5.

http://www.w3.org/TR/xhtml1/

I'm not sure your exact use case for wanting this, but if it's for clearing floats, you can do this instead and not have to worry about compatibility issues, especially with IE if it kicks into emulation mode.

<style type="text/css">
.clear-fix {
    clear: both !important;
    display: block !important;
    font-size: 0 !important;
    line-height: 0 !important;
    border: none !important;
    padding: 0 !important;
    margin: 0 !important;
    list-style: none !important;
}
</style>
<br class="clear-fix" />



回答2:


Closing tag is needed for elements that (can) contain something, such as div, a and body.

Slash is enough for elements that consist only of the element itself, such as img, link and br.




回答3:


The difference is that if you don't use a closing tag, you will be able to set only the tag's attributes.

If you need some content inside it, you need both a opening and a closing tag, having the content in between.

For example, if you need to skip a line using <br/>, you could technically also use <br></br>, but no one uses it that way, as a line skip will never have anything in between.

In the case of a <div>, you will probably have a lot of content inside it, needing a closing tag in the end.




回答4:


If you take a look at the HTML DTD (4.01 strict, as a 5 dtd is still in progress and has not been released yet), you will see that some elements are defined with an EMPTY, meaning these can be self closing. Elements that do not have this definition, cannot be self closing.

For example, the br element:

<!ELEMENT BR - O EMPTY                 -- forced line break -->

The div element is not defined this way, so it is never right to have a self closing div.

<!ELEMENT DIV - - (%flow;)*            -- generic language/style container -->



回答5:


If the element is self containing, and has everything that it needs to render itself without any innerHTML, than you can use the shorthand <hr /> otherwise you should use

 <div> InnerHTML here </div>


来源:https://stackoverflow.com/questions/7261375/closing-html-tag

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