0

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?

j08691
  • 190,436
  • 28
  • 232
  • 252
ayanokouji
  • 634
  • 9
  • 24

3 Answers3

2

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.

Ashesh
  • 3,230
  • 1
  • 20
  • 42
2

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>
Hatchet
  • 4,880
  • 1
  • 29
  • 42
1

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.

Kroltan
  • 4,424
  • 4
  • 31
  • 52