Images in HTML

The <img> tag is used to display images on a webpage. It is a self-closing tag that requires a src attribute, which specifies the path to the image file, and an alt attribute, which provides an alternative text description of the image.

Basic Image Example

Here's a basic example of using the <img> tag:

<img src="platypus.jpg" alt="A platypus swimming in water" />

This code will display the image located at platypus.jpg with a description that reads "A platypus swimming in water." If the image cannot be displayed, the alt text will appear in its place, making it important for accessibility.

Using the <figure> and <figcaption> Elements

The <figure> element is used to group images with their captions, making them easier to associate. You can include multiple images in a figure or use it to wrap other types of media. The <figcaption> element provides a caption for the content inside <figure>.

A platypus swimming in water
Figure 1: A platypus swimming in its natural habitat.

As well as linking from your own computer, you can also use absolute links.

A platypus diving
Source: The New York Times

Image Paths

When specifying the src attribute in an <img> tag, you can use either a relative path or an absolute path:

Image Attributes

The width and height attributes allow you to set the dimensions of an image in pixels, but it's often better to control the size with CSS to keep your code clean. Avoid using these attributes if the image is meant to be responsive.

You can also use CSS properties like max-width and height to ensure your images resize correctly based on screen size.

Responsive Images

To make your images responsive, use the following CSS properties:

img {
  max-width: 100%;
  height: auto;
}

This will ensure that the image scales down to fit within its container without exceeding its original dimensions.

Accessibility with Alt Text

Always include an alt attribute for every image. The text should describe the content and function of the image. If an image is purely decorative, you can use an empty alt attribute like this: alt="". This tells screen readers to skip the image, improving the accessibility of your site.

Next: Div vs. Span Previous: ID and Anchors