HTML Elements

Images

A picture is worth a thousand words.

-- common adage

Text is good for many purposes, but sometimes we just want to add a little more variety to our web pages. This is where images come to good use. The HTML <img> tag embeds an image into a document.

Common attributes

We can set attributes on an <img> element to specify where the image should be fetched from, what the image is of (in text format), the dimensions of the image and much more.

AttributeDescriptionRequired
srcpath of the image we want to embedyes
altalternative description of the imagehighly recommended, but image will still be shown if not specified
widthintrinsic width of the imageno
heightintrinsic height of the imageno

Code example

<img
alt="Picture of snow on a mountain top"
src="/learn/essential-front-end/html/elements/snow-mountain.jpg"
width="536"
height="354"
>

produces something like the below image (additional styles have been added on this page to make it look cooler).

Picture of snow on a mountain top
Picture of snow on a mountain top

Closing tag

The <img> tag is a so-called void or empty element which means that it cannot have any child nodes. Void element tags should not be closed in the usual fashion as shown in the example.

Accessibility

The alternative text attribute is technically optional, but should in practice be considered mandatory. This text should try to describe the image's content in a concise way. If an image is purely for decorative purposes, you can leave the attribute empty.

For example, in Norway, we have laws that say that all images must provide a description through the alternative text attribute and/or a caption.

Read more on MDN

<img>: The Image Embed element

Test yourself

Description

Add an image with the source

https://upload.wikimedia.org/wikipedia/en/7/73/Hyperion_cover.jpg

and the alternative text

Hyperion book cover showcasing a man looking towards a ship sailing on a grass dune

under the image source paragraph.

Tests

  1. 1 You should create an img element.
  2. 2 Your img element should have the source specified in the description.
  3. 3 Your img element should have the alternative text specified in the description.
Editor
Preview