Adding images

Adding images to your HTML documents helps create visually engaging content and improves the user experience. To add an image, you use the `<img>` element, which is an empty or self-closing element, meaning it doesn't require a closing tag. The `<img>` element requires a `src` attribute, which specifies the URL or the path to the image file.

Here are some examples of adding images to HTML:

  1. Basic image:
<img src="example-image.jpg" alt="An example image">

The `alt` attribute is used to provide a text description of the image. This description is displayed if the image cannot be loaded and is also important for accessibility, as screen readers use it to describe the image to visually impaired users.

  1. Image with width and height attributes:
<img src="example-image.jpg" alt="An example image" width="300" height="200">

The `width` and `height` attributes define the dimensions of the image in pixels. Setting these attributes can help improve the page layout as the browser knows the image size before it loads, which prevents content reflow.

  1. Image as a hyperlink:
<a href="">
  <img src="example-image.jpg" alt="An example image">

You can make an image clickable by wrapping it with an <a> (anchor) element. This creates a hyperlink that users can click to navigate to another page or website.

Here's a combined example demonstrating the use of images in various ways:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Adding Images Example</title>
    <h1>Adding Images</h1>
    <h2>Basic Image</h2>
    <img src="example-image.jpg" alt="An example image">
    <h2>Image with Width and Height Attributes</h2>
    <img src="example-image.jpg" alt="An example image" width="300" height="200">
    <h2>Image as a Hyperlink</h2>
    <a href="">
        <img src="example-image.jpg" alt="An example image">

When adding images to your HTML content, make sure to optimize the image size for the web to reduce loading times and improve the user experience. Also, always include the `alt` attribute with a meaningful description for accessibility purposes.

Was this page helpful?