This section talks about using HTML to place images in web pages. It does not address image formats, optimization and file sizes, compression, production workflow, or CSS for images. All of those topics are addressed elsewhere in this blog.
We place images onto web pages with the
<img> tag is the first tag we have encountered that does not have a matching closing tag. This makes sense, since everything about the image is specified by the tag’s attributes – the tag doesn’t “enclose” anything. The image attribute creates its own content, rather than the content being contained between an opening and closing tag.
To ensure compatibility with XHTML and XML, tags without an explicit closing tag are closed within themselves, like so:
(This internal closing is optional in HTML5).
By itself, the
<img> tag does nothing. Just as the
<a> element needs an
href attribute in order to work as a link, the
<img> tag needs a
src attribute to bring an image onto the page:
<img src="smile.jpg" />
(Note that the example above assumes that the
smile.jpg file is in the same location as the HTML page that uses it.)
A very important addition to the
<img> tag is the
alt attribute, which should be specified as soon as you insert the image into your web page, just as you specify the title of a page as soon as you create it. Every image must have a
<img src="smile.jpg" alt="Photograph of a smiling Norwegian fisherman" />
The easiest way to comprehend the
alt attribute is its original purpose: as an alternate text description of an image, as if you were describing it to someone who was blind.
Finally, note that as an inline tag,
<img> should be contained inside a block element. Usually (but not exclusively) that is a paragraph:
<p><img src="smile.jpg" alt="Smiling Norwegian fisherman" />The fjords of Norway are strange, lonely places, in which Great Auks look over a grey ocean that is frozen for half the year. It is in this harsh environment that Sigmund Erikson makes his living as a fisherman, trawling for cod…</p>
Again, this rule can be ignored for HTML5, but it is still a good practice to follow: think of an image as being an illustration for content, and thus part of a paragraph or heading.
If bitmapped text is part of the image, that text should be the
alt value, rather than a description of the image. This is commonly the case with corporate logos and banners, which typically should be wrapped in an
<h1><img src="ozymandias.jpg" alt="Ozymandius Corporation" /></h1>
Finally, if an image used on a page is purely decorative and has no meaning (i.e. if it was removed the content of the page would essentially remain the same), the
alt attribute must still be used, but it should be set to nothing at all: