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?
<picture-image><img><media><image>