Section 8: Images, Alt Text, Dimensions and Image Formats
Images are essential to modern websites. They help users understand content, explore products, recognize brands and interact with visual information. In this lesson, you will learn how to add images to HTML documents, write meaningful alternative text, control image dimensions, choose appropriate image formats and improve accessibility and performance.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Insert images using the HTML img element.
- Understand the src and alt attributes.
- Write useful alternative text for different image purposes.
- Distinguish informative, decorative and functional images.
- Set image dimensions and understand intrinsic image sizes.
- Compare JPEG, PNG, GIF, WebP, AVIF and SVG formats.
- Understand relative image paths and common loading problems.
- Use lazy loading, asynchronous decoding and image priorities appropriately.
- Organize images for accessibility, maintainability and performance.
- Identify common mistakes and test images in a browser.
2. What Is an HTML Image?
An image is visual content displayed inside a webpage. HTML uses the img element to embed an image into a document.
Unlike elements such as p and div, img is a void element. It does not have a closing tag and must not contain child elements.
Basic Syntax
<img src="images/profile.jpg"
alt="Developer working at a computer">Explanation:
imgidentifies the image element.srcspecifies the image resource URL.altprovides an alternative text representation of the image.
The browser retrieves the resource specified by src and displays the image when it loads successfully.
Example: A Website Logo
<img src="images/codementrix-logo.png"
alt="Codementrix">The alt text should describe the image's purpose in context. For a logo that links to the homepage, "Codementrix home" may be more useful than a long visual description.
3. Understanding the src Attribute
The src attribute specifies the URL of the image resource. It may use a relative URL, a root-relative URL or an absolute URL.
Relative Image Path
<img src="images/banner.jpg"
alt="Students learning web development">If the HTML document is located at the website root, the browser looks for the image inside the images directory relative to the document's base URL.
Root-Relative Image Path
<img src="/assets/images/logo.png"
alt="Company logo">This path starts from the root of the URL authority. It is useful when the image is available at a consistent root-relative URL.