santa
santa

Reputation: 12512

Closing HTML tag

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

<div></div>

vs.

<div />

Upvotes: 6

Views: 2899

Answers (5)

user888750
user888750

Reputation:

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" />

Upvotes: 3

Oded
Oded

Reputation: 499382

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 -->

Upvotes: 1

Layke
Layke

Reputation: 53206

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>

Upvotes: 0

FernandoH
FernandoH

Reputation: 865

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.

Upvotes: 2

Kokos
Kokos

Reputation: 9121

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.

Upvotes: 4

Related Questions