Courses / HTML · Advanced

HTML Images

Self-paced 40 sections 56 people viewed this
html html5 html tutorial learn html web development semantic html html forms html accessibility html seo html interview questions html projects beginner to advanced html

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:

  • img identifies the image element.
  • src specifies the image resource URL.
  • alt provides 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.

Absolute Image URL

<img src="https://example.com/images/product.jpg"
     alt="Product shown from the front">

Absolute URLs are useful when referencing images hosted on another domain or a dedicated image service.

Important Considerations

  • Use the correct filename and directory.
  • Check capitalization because many web servers use case-sensitive paths.
  • Use valid URLs and avoid accidental spaces or incorrect extensions.
  • Ensure the resource is accessible to the browser.
  • Remember that a relative image URL is resolved against the document's base URL, which can be affected by the base element.

4. Understanding the alt Attribute

The alt attribute supplies alternative text for an image. This text can communicate the image's relevant information when the image cannot be seen or when a user relies on assistive technology.

Alternative text is particularly important for people who use screen readers and for situations where an image fails to load.

Example: Informative Image

<img src="images/team.jpg"
     alt="The Codementrix development team at a workshop">

The alternative text communicates the relevant content rather than merely stating that the image is a photograph.

Example: Product Image

<img src="images/black-backpack.jpg"
     alt="Black backpack with two front pockets">

For a product page, relevant visual details may help a customer distinguish between similar products.

How to Write Good Alternative Text

  • Describe the information the image contributes to the page.
  • Keep the description concise and specific.
  • Consider the surrounding text and purpose of the image.
  • Avoid repeating information that is already clearly provided nearby.
  • Do not begin every description with "Image of" or "Picture of" unnecessarily.
  • Do not stuff alternative text with SEO keywords.

5. Informative, Decorative and Functional Images

The correct alternative text depends on the role of the image, not only on what it looks like.

A. Informative Images

An informative image communicates information that is important to understanding the page.

<img src="images/server-architecture.png"
     alt="The browser sends requests to the application server, which retrieves data from the database">

For a complex architecture diagram, a concise alt description can be supplemented with a complete explanation in the surrounding text.

B. Decorative Images

A decorative image adds visual decoration but does not provide additional information. Use an empty alt attribute for such images.

<img src="images/decorative-divider.png"
     alt="">

The empty alt attribute tells assistive technology that the image does not need to be announced as meaningful content.

Do not omit the alt attribute entirely just because an image is decorative. An absent alt attribute and an explicitly empty alt attribute have different accessibility implications.

C. Functional Images

An image used as the only content of a link or button should have alternative text that describes the action or destination.

<a href="/courses/">
    <img src="images/courses-icon.png"
         alt="Browse courses">
</a>

In this example, the link's purpose is to open the courses page. The alt text communicates that purpose.

D. Images with Captions

When an image needs a visible caption, use figure and figcaption.

<figure>
    <img src="images/html-structure.png"
         alt="Diagram showing the head and body sections of an HTML document">
    <figcaption>
        Basic structure of an HTML document.
    </figcaption>
</figure>

The figure element groups self-contained content, while figcaption provides its caption. A caption does not automatically replace the need for appropriate alt text.

6. When Should Alt Text Be Empty?

Use an empty alt attribute when the image is purely decorative or its information is already adequately represented in adjacent content and the image adds no additional meaningful information.

Example

<p>
    Learn HTML today.
    <img src="images/star-decoration.png" alt="">
</p>

The star is decorative, so announcing it to a screen reader would add unnecessary noise.

Common Alt Text Mistakes

  • Leaving alt missing on meaningful images.
  • Using filenames such as IMG_1234.jpg as descriptions.
  • Repeating entire paragraphs in alt text.
  • Using keyword-stuffed descriptions.
  • Describing an image's appearance when its actual purpose is to perform an action.
  • Adding redundant alt text to decorative images.

7. Image Width and Height Attributes

The width and height attributes provide the image's intended dimensions in CSS pixels. They help the browser reserve space before the image finishes loading.

Example

<img src="images/profile.jpg"
     alt="Profile of a web developer"
     width="400"
     height="300">

These dimensions describe the intended display size and aspect ratio. The browser does not need to download the image first to learn the layout space reserved by these attributes.

Why Dimensions Matter

  • They reduce unexpected layout shifts when images load.
  • They help the browser calculate the image's aspect ratio.
  • They make layout behavior more predictable.
  • They improve the user experience on slower connections.

Preserving Aspect Ratio

An image's aspect ratio is the relationship between its width and height.

For example, an image that is 1200 pixels wide and 800 pixels high has a 3:2 aspect ratio.

<img src="images/landscape.jpg"
     alt="Mountain landscape at sunrise"
     width="1200"
     height="800">

When resizing the image proportionally, preserve this ratio to avoid distortion.

Important Rule

Do not assign unrelated width and height values merely to force an image into a particular shape. If the image's actual aspect ratio differs from the intended display ratio, cropping or another deliberate presentation technique may be more appropriate.

8. Intrinsic Dimensions and Display Dimensions

Intrinsic dimensions are the dimensions associated with the image resource itself. Display dimensions describe how large the image appears on the page.

These dimensions can differ. For example, a 1600 by 1200 image can be displayed at 400 by 300 CSS pixels without changing the original file.

Example

<img src="images/large-photo.jpg"
     alt="A city skyline"
     width="400"
     height="300">

The browser may display the image at 400 by 300 CSS pixels, but the downloaded image may still contain millions of source pixels.

Reducing the displayed size does not necessarily reduce the file size downloaded by the browser. For efficient delivery, choose an appropriately sized image resource.

9. Responsive Image Sizing Basics

Images often need to fit different screen sizes. A common introductory technique is to let the image shrink within its containing element while preserving its proportions.

The following example uses inline CSS to demonstrate the principle. More complete responsive image selection is covered in the dedicated responsive images lesson.

<img src="images/course-banner.jpg"
     alt="HTML Mastery course banner"
     width="1200"
     height="600"
     style="max-width: 100%; height: auto;">

The max-width declaration prevents the displayed image from exceeding its container's available width. The automatic height preserves the aspect ratio.

In production projects, reusable styling should generally be placed in a CSS stylesheet rather than repeated inline.

10. Common Image Formats

Different image formats are suitable for different types of content. Choosing a format affects visual quality, file size, transparency support, animation and browser compatibility.

Format Typical use Important characteristics
JPEG / JPG Photographs Lossy compression; usually unsuitable for transparency.
PNG Screenshots, logos and transparent graphics Lossless compression; supports alpha transparency.
GIF Simple animations and legacy graphics Limited 256-color palette; supports animation and simple transparency.
WebP Photographs and web graphics Supports lossy and lossless compression, transparency and animation.
AVIF Photographs and complex web images Often offers strong compression; supports transparency and other advanced features.
SVG Logos, icons and scalable illustrations Vector graphics that scale without ordinary raster pixelation.

The best format depends on the image content, required quality, delivery requirements and supported browsers.

JPEG

JPEG is commonly used for photographs because lossy compression can substantially reduce file size.

<img src="images/team-photo.jpg"
     alt="Team members collaborating at a table"
     width="800"
     height="533">

PNG

PNG is useful for images requiring lossless compression or transparency, such as interface screenshots and some logos.

<img src="images/logo.png"
     alt="Codementrix logo"
     width="240"
     height="80">

GIF

GIF supports simple animation but has a limited color palette. For many modern web animations, video or other formats may offer better compression or visual quality.

<img src="images/loading-animation.gif"
     alt="Loading animation"
     width="100"
     height="100">

Ensure that an animation conveys useful information or is appropriate as a decorative asset. Avoid distracting or excessively flashing animations.

WebP

WebP supports lossy and lossless compression, transparency and animation. It can be an effective format for modern web image delivery.

<img src="images/product.webp"
     alt="Blue product package"
     width="600"
     height="600">

AVIF

AVIF can provide high compression efficiency, especially for photographic content. Always test the quality and performance of the resulting file for your particular use case.

<img src="images/landscape.avif"
     alt="Green valley surrounded by mountains"
     width="1200"
     height="800">

SVG

SVG is a vector image format. It is useful for logos, icons and illustrations that must remain sharp at different sizes.

<img src="images/brand-mark.svg"
     alt="Codementrix brand mark"
     width="160"
     height="160">

When using SVG files from untrusted sources, treat them as active web content rather than assuming that every SVG is harmless. Prefer trusted assets and avoid embedding untrusted SVG markup directly.

11. Using the Picture Element

The picture element allows the browser to choose among alternative image sources. It can be used to provide different formats or art-directed versions of an image.

This section introduces the concept; advanced responsive image selection using srcset and sizes is covered in the dedicated responsive images lesson.

Example: Format Fallback

<picture>
    <source srcset="images/hero.avif" type="image/avif">
    <source srcset="images/hero.webp" type="image/webp">
    <img src="images/hero.jpg"
         alt="Developer learning web technologies"
         width="1200"
         height="600">
</picture>

The browser evaluates the source elements in order and uses a suitable supported source. The img element provides the fallback image and carries the alternative text.

The picture element is useful when you have multiple representations of the same image or different crops for different display contexts.

12. Image Loading Performance

Images can account for a significant portion of a webpage's downloaded bytes. Efficient loading improves perceived performance, reduces data usage and can help important content appear sooner.

A. Lazy Loading

The loading="lazy" attribute allows the browser to defer loading an image until it approaches the visible area.

<img src="images/related-course.jpg"
     alt="Related web development course"
     width="640"
     height="360"
     loading="lazy">

Lazy loading is especially useful for images far below the initial viewport.

Do not apply lazy loading indiscriminately to the main hero image or another image that is likely to be the page's Largest Contentful Paint element. Delaying a prominent image can make the page appear slower.

B. Asynchronous Decoding

The decoding="async" attribute allows the browser to decode an image asynchronously where supported.

<img src="images/article-thumbnail.webp"
     alt="Article thumbnail about HTML"
     width="640"
     height="360"
     decoding="async">

This is a hint to the browser, not a guarantee that every browser will use a particular decoding strategy.

C. Fetch Priority

The fetchpriority attribute expresses the relative priority of a resource request.

<img src="images/hero.webp"
     alt="Main course banner"
     width="1200"
     height="600"
     fetchpriority="high">

Use high priority selectively for important images that need early loading. Do not set high priority on every image because excessive prioritization can reduce the benefit of resource scheduling.

D. Correctly Sized Image Files

Do not assume that a small displayed image requires a small download. Select or generate an image resource that suits the intended display size and quality.

For example, downloading a 5000-pixel photograph to display a small thumbnail can waste bandwidth when a smaller version would be sufficient.

13. Image Dimensions and Layout Stability

When an image loads without reserved space, the page layout may shift as the browser discovers its dimensions. Providing width and height attributes helps the browser reserve the appropriate aspect ratio before the resource finishes loading.

Example

<img src="images/course-cover.webp"
     alt="HTML Mastery course cover"
     width="1200"
     height="675"
     loading="lazy">

Use accurate dimensions that reflect the source image's aspect ratio. If the image is intentionally cropped, ensure the reserved dimensions reflect the intended presentation.

14. Image Security and Reliability

Images may be served from your own website or from external domains. External image hosting introduces additional availability, privacy and performance considerations.

  • Use trusted image sources.
  • Verify that the resource can be loaded over the page's supported security scheme.
  • Avoid relying on third-party images that may disappear or change without notice.
  • Use an appropriate Content Security Policy when your application needs to restrict image sources.
  • Do not assume that hiding an image or using alt text validates the safety of its source.
  • Test image behavior when resources are missing or blocked.

Browsers generally block insecure active or passive resource requests in many HTTPS contexts according to mixed-content rules. Use secure image URLs on secure websites.

15. Common Image Mistakes

Mistake 1: Missing Alternative Text

<img src="images/product.jpg">

For informative images, provide suitable alt text. For decorative images, use alt="". The correct choice depends on the image's purpose.

Mistake 2: Incorrect File Path

<img src="image/product.jpg"
     alt="Product">

If the actual directory is named images rather than image, the browser may be unable to find the file. Verify the path and filename.

Mistake 3: Distorted Images

<img src="images/landscape.jpg"
     alt="Mountain landscape"
     width="200"
     height="600">

These dimensions may distort an image whose source aspect ratio is different. Preserve the aspect ratio or intentionally crop the image.

Mistake 4: Using Lazy Loading for Every Image

Lazy loading every image, including a prominent above-the-fold image, may delay important visual content. Apply loading strategies according to the image's position and importance.

Mistake 5: Choosing a Format Without Considering Its Purpose

JPEG may work well for photographs, while PNG may be better for certain transparent graphics. WebP and AVIF can offer efficient delivery. Choose based on actual visual quality, file size and browser support requirements.

Mistake 6: Repeating Captions in Alt Text

If a caption already provides the same information, avoid unnecessarily repeating it in the alternative text. Decide what information users need from the image in the context of the page.

16. Real-World Project: Course Card Images

Imagine you are creating a Codementrix course listing. Each course card displays a cover image, a title and a short description.

<article>
    <img src="images/html-course.webp"
         alt="HTML code displayed in a code editor"
         width="800"
         height="450"
         loading="lazy"
         decoding="async">

    <h2>HTML5 Mastery</h2>

    <p>
        Learn HTML from fundamentals to advanced
        concepts with practical examples.
    </p>

    <a href="/courses/html-mastery/">
        Explore HTML5 Mastery
    </a>
</article>

In this example:

  • The img element displays the course cover.
  • The alt text describes the meaningful content of the image.
  • The width and height attributes reserve space and describe the aspect ratio.
  • Lazy loading is appropriate if the card is outside the initial viewport.
  • The heading and description provide text information about the course.
  • The anchor provides navigation to the course page.

If the cover image is merely decorative and the title already communicates everything necessary, use an empty alt attribute instead.

17. Practical Exercises

Exercise 1: Add Images to a Webpage

Create a page containing a profile image, a course cover and a decorative divider. Use the appropriate alt attribute for each image.

Exercise 2: Compare Image Formats

Choose a photograph, a transparent logo and a simple illustration. Export them in suitable formats and compare file sizes and visual quality.

Exercise 3: Fix Image Dimensions

Create an image with incorrect dimensions. Correct the width and height attributes so the image retains its aspect ratio.

Exercise 4: Improve Loading Performance

Create a page containing several images. Use accurate dimensions, apply lazy loading to suitable below-the-fold images and avoid delaying the main hero image unnecessarily.

Exercise 5: Accessibility Audit

Review a webpage and identify images with missing alt text, unnecessary descriptions, redundant captions or incorrect descriptions. Improve each image's alternative text based on its purpose.

Exercise 6: Build a Course Card

Create three course cards with image, heading, description and navigation link. Ensure that every image has appropriate dimensions and alternative text.

18. Section 8 Quiz: Test Your Understanding

Answer the following 10 questions after completing the lesson. The answer key and explanations appear below the questions.

Question 1: Basic Image Syntax

Which HTML element embeds an image in a webpage?

  1. <picture-image>
  2. <img>
  3. <media>
  4. <image>

Question 2: Alternative Text

What is the primary purpose of the alt attribute on an informative image?

  1. To set the image's display width.
  2. To control how the browser compresses the image.
  3. To provide a text alternative for the image's relevant information.
  4. To force the browser to download the image immediately.

Question 3: Decorative Images

Which is the appropriate alt attribute for an image that is purely decorative and adds no meaningful information?

  1. alt="decorative image"
  2. alt="image"
  3. Omit the alt attribute completely.
  4. alt=""

Question 4: Image Dimensions

Why should developers specify accurate width and height attributes on images when possible?

  1. They guarantee that the image will never fail to load.
  2. They help the browser reserve layout space and reduce unexpected layout shifts.
  3. They automatically convert JPEG images into WebP.
  4. They guarantee that every image is displayed at its original pixel dimensions.

Question 5: True or False

Setting an image's HTML width attribute to 200 guarantees that the browser downloads a source image only 200 pixels wide.

  1. True
  2. False

Question 6: Choosing an Image Format

Which format is specifically designed for vector graphics that can scale without ordinary raster pixelation?

  1. JPEG
  2. GIF
  3. SVG
  4. PNG

Question 7: Lazy Loading

Where is loading="lazy" generally most appropriate?

  1. On every image, regardless of its position.
  2. On images far below the initial viewport that do not need to load immediately.
  3. Only on the first visible hero image.
  4. On images that must be displayed before any other page content.

Question 8: Multiple Correct Answers

Which statements about HTML images are correct? Select all that apply.

  1. The img element is a void element and must not contain child elements.
  2. Meaningful alt text should describe the image's purpose in context.
  3. Displaying an image at a small CSS width always guarantees a small downloaded file.
  4. The picture element can provide alternative image sources.

Question 9: True or False

An image used as the only content of a link should have alternative text that communicates the link's purpose or destination.

  1. True
  2. False

Question 10: Image Performance

Which attribute is used to express a high relative fetch priority for an important image?

  1. loading="lazy"
  2. decoding="async"
  3. fetchpriority="high"
  4. alt="high"

19. Quiz Answer Key and Explanations

Check your answers and review the explanations to reinforce the concepts covered in this section.

Answer 1: B — <img>

The img element embeds an image resource in the document. The src attribute specifies the resource, while alt provides its text alternative.

Answer 2: C — Provide a text alternative

The alt attribute communicates the image's relevant information when the image cannot be seen or when assistive technology is used. Width, compression and fetch priority are controlled separately.

Answer 3: D — alt=""

An explicitly empty alt attribute indicates that the image is decorative and does not need a text alternative. Omitting alt entirely can cause the image's filename or URL to be exposed by some assistive technologies.

Answer 4: B — Reserve layout space

Accurate dimensions allow the browser to calculate the image's aspect ratio and reserve space before the image finishes loading. This can reduce layout shifts but does not guarantee successful loading.

Answer 5: False

The width attribute describes the intended display width in CSS pixels. It does not necessarily change the source file or the number of pixels downloaded. A separately optimized image resource may be needed to reduce download size.

Answer 6: C — SVG

SVG uses vector graphics. Shapes are represented mathematically rather than as a fixed grid of pixels, allowing them to scale smoothly in ordinary rendering scenarios.

Answer 7: B — Images far below the viewport

Lazy loading can defer images that are not immediately needed. Important above-the-fold images, especially the main hero image, should not be delayed without a good reason.

Answer 8: A, B and D

  • A is correct because img is a void element and does not accept child content.
  • B is correct because alt text should reflect the image's meaning and purpose in context.
  • C is incorrect because CSS display size does not guarantee that the downloaded resource is small.
  • D is correct because picture and its source elements allow the browser to select among alternative image resources.

Answer 9: True

When an image is the only content of a link, its alternative text normally provides the link's accessible name. The description should communicate the destination or action rather than merely describing irrelevant visual details.

Answer 10: C — fetchpriority="high"

The fetchpriority attribute communicates a relative priority hint to the browser. Use it selectively for important resources. The loading and decoding attributes serve different purposes.

20. Final Revision Checklist

  • I can create images using the img element and src attribute.
  • I understand absolute and relative image paths.
  • I can write meaningful alt text for informative and functional images.
  • I know when to use an empty alt attribute.
  • I understand width, height and aspect ratio.
  • I can choose appropriate image formats for different content.
  • I understand the purpose of picture and alternative sources.
  • I can use lazy loading and fetch priority appropriately.
  • I know how to avoid common image accessibility and performance mistakes.
  • I can build an accessible course card with a properly described image.

Lesson Completion

Congratulations! You have completed Section 8 of Codementrix HTML5 Mastery.

You now understand how to embed images, write meaningful alternative text, choose appropriate image formats, specify dimensions and apply foundational image performance techniques.

Next lesson: Section 9 — Ordered, Unordered and Description Lists.