开发者

question regarding img tag in html

开发者 https://www.devze.com 2022-12-17 20:59 出处:网络
Should the <img> tag be wrapped in a <p> tag or can it be ju开发者_如何学Cst used without a <p> tag?<img> is an inline element and as such needs to be placed inside a block lev

Should the <img> tag be wrapped in a <p> tag or can it be ju开发者_如何学Cst used without a <p> tag?


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


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, ...)


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.


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;
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消