tags:

views:

249

answers:

4

Hi All,

I was just wondering if the <img> tag should be wrapped in <p> tag or it can be just used without <p> tag.

Thanks

+4  A: 

According to the HTML 4.01 spec may the IMG tag appear inside any element which allow %inline elements, that means it cannot be directly inside the <body> tag, but it may very well be inside an <div> tag instead of the <p>-tag.

EDIT: this means that the img tag may be inside any block level tag (div, p, li, ...)

elzapp
+3  A: 

I can't comment or vote yet, but the answer by Younes is wrong. You cannot write an image tag like this:

<img src=""> </img>

Also, the best place to look for what is allowed and not allowed for HTML tags, the best source is the actual specs, available on the W3C website. Here's the link for the img tag for HTML 4.01:

http://www.w3.org/TR/html4/struct/objects.html#h-13.2

And here's the link showing the differences between HTML 4.01 and XHTML 1.0 (which is where the comes from:

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

In general, an img can be wrapped by most container tags (some exceptions, like pre, do exist), but it is not required. If you are trying to make your HTML semantic, then most often, it won't make sense to have your img inside a paragraph tag, but it might make sense to put it into a div.

Charles Boyung
+6  A: 

<img> is an inline element and as such needs to be placed inside a block level element to validate.

Something like a <p>, <div>, <h1>, or a <li> would suffice.

Inline elements cannot be placed directly inside the body element; they must be wholly nested within block-level elements.

Jonny Haynes
Just to clarify to the OP, that the above means that the `img` can be anywhere inside a block element. The block element does not need to 'directly' wrap like this `<p><img></p>`. If you have a wrapper div on your page everything is in a block level element, I guess.
Gazzer
A: 

If you want to make it act like a block the ever useful

.somewhere img
{
    display:block;
}

is good. (As noted above it needs to be a descendent of a block level element but that can be any level above obviously, so you don't need to do this all the time:

 <div><img></div>

If you have a link around the image, you can do the same display:block as above to the a element.

 a.somewhere, a.somewhere img
 {
    display:block;
 }
Gazzer
You make it appear as a block this way, but it's still not a block level element, which means that even though you style it as block, you may NOT use img directly inside `<body>` (but you already noted this, I just didn't read it all before commenting)
elzapp
Yes, as you've noted the block level issue is pretty much moot if you have a wrapper div like this `<body><div id='wrapper'>CONTENT</div></body>` since all your content is inside the wrapper div.
Gazzer