Images in HTML


In the beginning, the Web was just text, and it was really quite boring. Fortunately, it wasn't too long before the ability was added to embed images (and other more interesting types of content) inside web pages. There are other types of multimedia to consider, but it is logical to start with the humble <img> element, used to embed a simple image in a webpage. In this article we'll look at how to use it in depth, including basics, annotating it with captions using <figure>, and how it relates to CSS background images.

Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with HTML fundamentals (as covered in Getting started with HTML.)
Objective: To learn how to embed simple images in HTML, annotate them with captions, and how HTML images relate to CSS background images.


为了将一幅简单的图片展示到网页上我们通常会使用 <img> 元素。它是一个空元素(不需要包含内容也不需要闭合标签)最少只需要一个src (pronounced sarc, sometimes spoken as its full title, source)来使其生效。src 属性包含了指向我们想要引入的图片的路径,可以是相对路径或绝对路径,就像 <a> 元素中的 href 属性一样 (你可以阅读 A quick primer on URLs and paths 来唤醒一下你的记忆.)

举个例子来看,如果你有一幅文件名为 dinosaur.jpg 的图片并且存放在和你的 HTML  页面相同路径下,那么你可以像下面这样来将图片放到页面上展示:

<img src="dinosaur.jpg">

如果这张图片存储在和 HTML 页面同路径 image 文件夹的子路径下 (which is what Google recommends for SEO/indexing purposes), 那么你可以采用如下形式:

<img src="images/dinosaur.jpg">


Note: Search engines also read image filenames and count them towards SEO — you should therefore give your image a descriptive filename (dinosaur.jpg is better than img835.png.)


<img src="">

但是这种方式是不被推荐的,这样做只会使浏览器做更多的工作,例如重新通过 DNS 再去寻找 IP 地址。但是人们基本上总是把图片和 HTML 放在同一个存放网站的服务器上。

Warning: Most images are copyrighted. Do not display an image on your webpage unless 1) you own the image, 2) you have received explicit, written permission from the image's owner, or 3) you have ample proof that the image is, in fact, in the public domain. Copyright violations are illegal and immoral.

In addition, never point your src attribute at an image hosted on someone else's website that you don't have permission to link to. This is called "hotlinking" — again, stealing someone's bandwidth is illegal and wrong (it also slows your page down, and you have no control over whether the image is removed or replaced with something embarrassing.)


A basic image of a dinosaur, embedded in a browser, with Images in HTML written above it

Note: Elements like <img> and <video> are sometimes referred to as replaced elements, because the element's content and size is defined by an external resource (like an image or video file), not the contents of the element itself. 

Note: You can find the finished example from this section running on Github (see the source code too.)


下一个我们讨论的属性是 alt — 它的值应该是该图片的文字描述,用于在图片出于某种原因无法展现时在页面上显示。例如,上面的例子可以做如下改进:

<img src="images/dinosaur.jpg"
     alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth">

测试alt 属性最简单的方式就是故意拼错图片文件名,这样浏览器就无法找到该图片从而显示可替换的文字。如果我们将上例的图片文件名改为 dinosooooor.jpg。那么浏览器不会正确的显示图片而是会像下面一样显示出替换的文字:

The Images in HTML title, but this time the dinosaur image is not displayed, and alt text is in its place.

那么,为什么我们需要 alt 属性呢? 想一想下面这些情形:

  • 用户在视力上有障碍,通过 screen reader 来浏览我们的网站 — 在这样的情况下,拥有一段描述图片的文字是非常有用的!i
  • 就像上面所说的,你也许会吧图片的路径或文件名拼错。
  • 浏览器不支持该图片类型。某些用户仍在使用只显示文字的浏览器,类似 Lynx,,将会把图片替换为描述的文字。
  • 你想要提供一些文字描述来给搜索引擎使用— 例如搜索引擎可能会将图片的文字描述和查询条件进行匹配。
  • 用户关闭的图片显示以减少数据的传输(尤其是在使用智能手机浏览时,因为有些国家的宽带速率是有限且昂贵的)

什么才是真正应该写在 alt 属性中的文字呢? 这取决于为什么这些图片会出现在这些地方(换句话说,如果没了这些图片,你所想表达的东西会失去些什么):

  • Decoration. If the image is just decoration and isn't part of the content, add a blank alt="" so that, for example, a screen reader doesn't waste time reading out content that is no use to the user. Decorative images don't really don't belong in your HTML anyway — CSS background images should be used for inserting decoration — but if it is unavoidable, alt="" is the best way to go.
  • Content. If your image provides significant information, provide the same information in a brief alt text, or better yet, in the main text that everybody can see. Don't write redundant alt text (how annoying would it be for a sighted user if all the paragraphs were written twice in the main content?) If the image is described adequately by the main text body, you can just use alt="".
  • Link. If you put an image inside <a> tags to turn an image into a link, you still must provide accessible link text — in such cases you may either write it inside the same <a> element or inside the image's alt attribute if that works better.
  • Text. You should not put your text into images (if your main heading needs a drop shadow, for example, use CSS for that rather than putting the text into an image.) If you really can't avoid doing this, however, you should supply the text inside the alt attribute.

The key is to deliver a usable experience even when the images can't be seen, where users aren't missing any of the content. Try turning off images in your browser and see how things are. You'll soon realise how unhelpful alt text such as "logo" or "my favourite place" is, if the image cannot be seen.

Note: WebAIM's Alternative text guide provides more detailed guidance for alternative text, and is a good read if you want more information.

Width and height

You can use the width and height attributes to specify the width and height of your image (you can find your image's width and height in a number of ways, for example on the Mac you can use Cmd + I to get the info display up for the image file.) Returning to our example, we could do this:

<img src="images/dinosaur.jpg"
     alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth"

This doesn't result in much difference to the display under normal circumstances, but if the image isn't being displayed (for example the user has just navigated to the page, and the image hasn't loaded yet,) you'll notice that the browser leaves a space for the image to appear in:

The Images in HTML title, with dinosaur alt text, displayed inside a large box that results from width and height settings

This is a good thing to do — it results in the page loading quicker and more smoothly.

You shouldn't however alter the size of your images using HTML attributes — if you set the size too big you'll end up with images that look grainy/fuzzy; too small, and you'll be wasting bandwidth by downloading an image that's far bigger than you need. The image may also end up looking distorted if you don't maintain the correct aspect ratio. You should use an image editor to put your image at the correct size before putting it on your webpage.

Note: If you do end up needing to alter an image's size, you should use CSS rather than HTML.

Image titles

In the same way as with links, you can also add title attributes to images to provide further supporting information if needed. In our example, we could do this:

<img src="images/dinosaur.jpg"
     alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth"
     title="A T-Rex on display in the Manchester University Museum">

This gives us a tooltip, just like with link titles:

The dinosaur image, with a tooltip title on top of it that reads A T-Rex on display at the Manchester University Museum

Image titles aren't essential to include by any means, and it is often better to include such supporting information in the main article text, rather than attached to the image. They are useful in some circumstances however, for example in an image gallery when you have no space for captions.

Active learning: embedding an image

Ok, your turn! In this active learning section we'd like you to play with a simple embedding exercise. You are provided with a basic <img> tag; we'd like you to embed the image located at the following URL:

Yes, earlier we said to never hotlink to images on other servers. But this is just for demo purposes — we'll let you off just this once.

We would also like you to:

  • Add some alt text and check that it works by misspelling the image URL.
  • Set the image's correct width and height (hint; it is 200px wide and 171px high), then experiment with other values to see what the effect is.
  • Set a title on the image.

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer.

Annotating images with figures and figure captions

Speaking of captions, there are a number of ways that you could add a caption to go along with your image. For example, there would be nothing to stop you doing this:

<div class="figure">
  <img src="images/dinosaur.jpg"
       alt="The head and torso of a dinosaur skeleton;
            it has a large head with long sharp teeth"

  <p>A T-Rex on display in the Manchester University Museum.</p>

This is ok — it contains the content you need, and is nicely stylable using CSS. But there is a problem here — there is nothing that semantically links the image to its caption, which can cause problems for screen readers, for example (when you have 50 images and captions, which caption goes with which image?)

A better solution is to use the HTML5 <figure> and <figcaption> elements, which are created for exactly this purpose — to provide a semantic container for figures that clearly links the figure to the caption. Our above example could be rewritten like this:

  <img src="images/dinosaur.jpg"
       alt="The head and torso of a dinosaur skeleton;
            it has a large head with long sharp teeth"

  <figcaption>A T-Rex on display in the Manchester University Museum.</figcaption>

The <figcaption> element tells browsers and assistive technology that the caption describes the other content of the <figure> element.

Note: From an accessibility viewpoint, captions and alt text have distinct roles. Captions benefit even people who can see the image, whereas alt text provides the same functionality as an absent image. Therefore, captions and alt text shouldn't just say the same thing, because they both appear when the image is gone. Try turning images off in your browser and see how things look.

Note that a figure doesn't have to be an image — a figure is an independent unit of content that:

  • Expresses your meaning in a compact, easy-to-grasp way
  • Could go in several places in the page's linear flow
  • Provides essential information supporting the main text

A figure could be several images, a code snippet, audio or video, equations, a table, or something else.

Active learning: creating a figure

In this active learning section, we'd like you to take the finished code from the previous active learning section, and turn it into a figure:

  • Wrap it in a <figure> element.
  • Copy the text out of the title attribute, remove the title attribute, then put the text inside a <figcaption> element below the image.

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer.

CSS background images

You can also use CSS to embed images into webpages (and JavaScript, but that's another story entirely.) The CSS background-image property — and the other background-* properties — are used to control background image placement. For example, to place a background image on every paragraph on a page you could do this:

p {
  background-image: url("images/dinosaur.jpg");

The resulting embedded image is arguably easier to position and control than HTML images, so why bother with HTML images? As hinted at above, CSS background images are for decoration only — if you just want to add something pretty to your page to enhance the visuals, this is fine, but such images have no semantic meaning at all — they can't have any text equivalents, are invisible to screen readers, etc. That is where HTML images shine.

So, if an image has meaning in terms of your content, you should use an HTML image. If an image is purely decoration, you should use CSS background images.

Note: You'll learn a lot more about CSS background images in our CSS topic.


That's all for now — we have covered images and captions in detail. In the next article we'll move up a gear, looking at how to use HTML to embed video and audio in web pages.


 此页面的贡献者: MinimalistYing
 最后编辑者: MinimalistYing,