Images in HTML: Displaying and Optimizing

Discover how to embed images into your web pages using the `` tag. Learn about image attributes like `src`, `alt`, `width`, and `height` and best practices for image optimization.


Images in HTML: Displaying and Optimizing

Introduction

Images are a crucial part of web design, making content more engaging and visually appealing. This guide will cover how to embed images into your web pages using the <img> tag and discuss best practices for image optimization.

The <img> Tag

The <img> tag is used to embed images into an HTML document. It's an empty element, meaning it has no closing tag. The image is displayed at the point where the tag appears in the HTML.

Key Attributes

  • src: Specifies the URL (path) to the image. This is *required*.
  • alt: Provides alternative text for the image, displayed if the image cannot be loaded. Also crucial for accessibility (screen readers). This is *required* and should be descriptive!
  • width: Sets the width of the image in pixels.
  • height: Sets the height of the image in pixels.

Example:

A beautiful landscape
<img src="example.jpg" alt="A beautiful landscape" width="500" height="300">

Important Note: While width and height attributes are still supported, it's best practice to control image dimensions using CSS for more responsive and flexible layouts. Using them directly in the HTML will lock the image to that particular size, unless overridden by CSS.

Image Paths (src attribute)

The src attribute specifies the location of the image file. This can be an absolute URL (linking to an image on another website) or a relative URL (linking to an image within your own website's file structure).

  • Absolute URL: <img src="https://www.example.com/images/myimage.jpg" alt="Image from Example.com">
  • Relative URL: <img src="images/myimage.jpg" alt="Image on this site"> (Assumes the image is in a folder named "images" in the same directory as the HTML file.)
  • Relative URL (parent directory): <img src="../images/myimage.jpg" alt="Image from parent directory"> (Goes up one directory level.)

Using relative URLs is generally preferred for images within your own website, as it makes your site more portable. If you move your website to a different server, the relative paths will still work.

Alternative Text (alt attribute)

The alt attribute provides alternative text for the image. This text is displayed if the image cannot be loaded (e.g., due to a broken link or network error). More importantly, it's used by screen readers to describe the image to visually impaired users. Always provide a meaningful alt attribute.

Best Practices for alt text:

  • Be descriptive and concise. Explain what the image shows.
  • If the image is purely decorative and doesn't convey any information, use an empty alt attribute: alt="". This tells screen readers to ignore the image.
  • Don't start the alt text with "Image of..." or "Picture of...". Screen readers already know it's an image.
Image failed to load: A landscape with mountains and a lake.

(Since 'broken_image.jpg' likely doesn't exist, you'll see the alt text)

Image Optimization

Optimizing images is crucial for improving website performance and user experience. Large image files can significantly slow down page load times.

Key Optimization Techniques:

  • Choose the right file format:
    • JPEG: Best for photographs and images with lots of color.
    • PNG: Best for images with sharp lines, text, and transparency.
    • GIF: Best for simple animations and images with limited colors (though PNG is often a better choice now).
    • WebP: A modern image format that provides superior lossless and lossy compression for images on the web. Highly recommended where supported.
    • AVIF: An even more modern image format offering potentially even better compression than WebP, but with slightly less browser support.
  • Compress images: Use image compression tools (e.g., TinyPNG, ImageOptim, or tools built into photo editors) to reduce file size without sacrificing too much quality.
  • Resize images: Don't upload images larger than necessary. Resize them to the dimensions they will be displayed on the webpage.
  • Use responsive images: Use the <picture> element or the srcset attribute of the <img> tag to serve different image sizes based on the user's device and screen size. This can drastically reduce bandwidth usage for mobile users.
  • Lazy loading: Use the loading="lazy" attribute on the <img> tag to defer loading of images that are off-screen until the user scrolls near them. This improves initial page load time.

Example of lazy loading:

A lazy loaded landscape
<img src="landscape.jpg" alt="A lazy loaded landscape" width="600" height="400" loading="lazy">

Responsive Images (srcset and sizes attributes)

Serving different image sizes based on the user's screen size is crucial for responsive web design. The srcset and sizes attributes allow you to achieve this.

  • srcset: Defines a list of image URLs along with their pixel density descriptors (e.g., `1x`, `2x`) or width descriptors (e.g., `320w`, `640w`).
  • sizes: Defines a set of media conditions (e.g., `(max-width: 600px) 480px`) and corresponding image sizes. The browser uses this to determine which image from the srcset is most appropriate.
A responsive landscape
<img srcset=" landscape-320.jpg 320w,
landscape-480.jpg 480w,
landscape-800.jpg 800w "
sizes="(max-width: 600px) 480px, 800px"
src="landscape-800.jpg"
alt="A responsive landscape" >

In this example:

  • The browser will choose `landscape-320.jpg` if the viewport width is less than or equal to 600px and the image should occupy 480px.
  • Otherwise, the browser will choose `landscape-800.jpg` if the image should occupy 800px. If none of the srcset images are suitable, the browser will fall back to the src attribute, `landscape-800.jpg`.

The <picture> Element

The <picture> element offers more advanced control over responsive images. It allows you to specify multiple <source> elements, each with its own media query and srcset. The browser will choose the first <source> element that matches the media query.

A landscape
<picture>
  <source media="(max-width: 600px)" srcset="landscape-small.jpg">
  <source media="(min-width: 601px)" srcset="landscape-large.jpg">
  <img src="landscape-default.jpg" alt="A landscape">
</picture>

In this example:

  • If the viewport width is less than or equal to 600px, `landscape-small.jpg` will be used.
  • If the viewport width is greater than 600px, `landscape-large.jpg` will be used.
  • The <img> element is used as a fallback if none of the <source> elements match. It *must* be the last child of the <picture> element.