ruyili
ruyili

Reputation: 703

html - Difference between these two tags?

What is the difference between <element></element> and <element />? I've been reading some HTML tutorials, and some use

<img src="foo.png" alt="foo" />

while others use

<img src="bar.png" alt="bar"></img>

What is the difference? When I try both, it doesn't seem to affect anything. Now, I'm just going to make a wild guess and say that this:

<img src="bar.png" alt="bar"> is if you want to put something in between? </img>

Can anyone confirm my guess and/or tell me what the difference is?

Upvotes: 0

Views: 60

Answers (3)

Kroltan
Kroltan

Reputation: 5156

There are specifically 3 kinds of tags in HTML. Each standard tag is documented as of which type it should be (I say should because most browsers allow for tags with the wrong type).

  • Void tags: Are composed only by the start tag, with no closing. <x> Examples:

    <br>
    <hr>
    
  • Self-closing tags: Are start tags with the closing portion at the end. <x /> Examples:

    <script />
    <style />
    <img />
    
  • Closing tags: Are the common start-content-end tags. <x> ... </x> Examples:

    <div> ... </div>
    <a> ... </a>
    <em> ... </em>
    

If you want maximum theoretical vaildity on your HTML, this is super important, but in practice, most browsers treat a closing tag with no content as equivalent to self-closing and void tags. This means that albeit invalid, things like this will work:

<img src="a.png"></img>
<br />

BUT!

You should never do this:

<div> blablabla

Closing tags must have a corresponding close otherwise you can mess up the markup pretty heavily.

If you stick to the standard, there will be no surprises.

Upvotes: 1

Hatchet
Hatchet

Reputation: 5428

A void tag requires no end tag, and in fact, must not specify an end tag (and thus, cannot have any content), as per the spec. The <img> tag is one of those void tags. Thus, if you run the following code through a validator, you'll get an error on line 10: Stray end tag img.

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <p>
            <img src="#" alt="">
            <img src="#" alt="" />
            <img src="#" alt=""></img>
        </p>
    </body>
</html>

Upvotes: 2

Ashesh
Ashesh

Reputation: 3589

First,

<img src="bar.png" alt="bar"> is if you want to put something in between? </img> 

is not correct but I can understand what you mean to ask.

The ones of the form <element /> are called self-closing tags.

Upvotes: 2

Related Questions