Adding Images to Your Page

Bring pictures onto your website

6 min read

Text can only carry a website so far. Sooner or later you will want to add a photo, an icon, or a drawing, and that is exactly what the image tag is for.

The img tag

Images use the <img> tag, and it works a little differently from every tag you have met so far: it does not have a closing tag at all. All the information it needs goes inside a single opening tag, using attributes just like the link tag you just learned.

<img src="cat.jpg" alt="An orange cat sleeping on a windowsill">

The src attribute, short for "source", tells the browser which image file to load. The alt attribute provides a text description of the image.

Why alt text matters

The alt attribute is not optional in any meaningful sense. It is read aloud by screen readers for visitors who cannot see the image, and it is shown as backup text if the image fails to load for any reason. A good alt description is short and describes what is actually in the picture.

<img src="sunset.jpg" alt="Sunset over the ocean with orange and pink clouds">
If an image is purely decorative and adds no real information, it is fine to use an empty alt like alt="". But for any image that matters to the page's meaning, always write a real description.

Where do image files come from?

The value of src is a path to an image file, very much like the file names you saw with links in the last lesson. If your image file is stored in the same place as your page, you can just use its name, like photo.jpg. Common image file types you will run into are .jpg, .png, and .gif.

Sizing images

By default, an image shows up at its natural size, which can sometimes be much bigger than you want on the page. You can suggest a size using width and height attributes, measured in pixels.

<img src="cat.jpg" alt="An orange cat sleeping" width="300" height="200">

You have now met the three attributes you will use on almost every image you ever add: src to say where the file is, alt to describe it in words, and optionally width and height to control its size. Combined with the links from the last lesson, you can now build a page with real pictures and real navigation between pages.

Quick check

Q1 What does the alt attribute on an image do?

Q2 Does the <img> tag need a closing tag like </img>?

Want to save your progress? It's free.

Create a free account