People eat with their eyes, and a café is no exception: the logo, the storefront, a freshly baked croissant… Images make a website recognisable and appealing, but they are also one of the resources most often used badly: without alt text, with huge file sizes or making the page "jump" while it loads. In this lesson you will learn how to insert images with the img element, how to write good alt text (and how to tell when it should be left empty), how to state their dimensions so that the layout stays stable, how to choose the right format and how to turn an image into a link. By the end, The Blue Cup will have its logo on every page and a gallery with the storefront and its star products.
Contents
- The
imgelement and thesrcattribute - The
altattribute: describing the image - Decorative images and empty
alt widthandheight: avoiding layout shifts- Image formats for the web
- Images as links
altversustitle- Project: The Blue Cup's logo and gallery
The img element and the src attribute
Images are inserted with the img element, an empty element (it has no content and no closing tag, like br):
<img src="img/storefront.jpg" alt="The Blue Cup's storefront, with a blue awning and tables on the pavement">| Attribute | Required | Purpose |
|---|---|---|
src |
Yes | Path or URL of the image file |
alt |
Yes (it must always be there) | Alternative text that replaces the image |
width, height |
Highly recommended | Intrinsic dimensions of the image, in pixels |
The src attribute (source) follows the same path rules as href:
- Relative, for the images in your project:
img/storefront.jpgfrom a page in the root folder;../img/storefront.jpgfrom a subfolder. - Full URL, for an image hosted on another site:
https://photos.example/coffee.jpg. Use this with caution: if the other site changes or deletes the image, it will disappear from your page, and you must also have permission to use it.
By default, img behaves like an inline element: it sits within the line of text, like a very large word. That's why you can put it inside a p. To position and size it precisely you will use CSS (Module 8).
If the path is wrong, the browser shows a broken image icon and, in its place, the alt text. In the Network panel of DevTools, the image will appear in red with a 404.
The alt attribute: describing the image
The alternative text (alt) is what replaces the image when it can't be seen:
- Blind and partially sighted people who use a screen reader hear the
altinstead of seeing the image. - If the image doesn't load (slow connection, wrong path), the browser shows the
alt. - Search engines use it to understand what the image shows.
Good alt text conveys the information or the purpose of the image in its context, briefly:
| Image | Bad alt |
Good alt |
|---|---|---|
| Photo of a croissant on the menu | alt="image" |
alt="Golden, flaky butter croissant" |
| The same photo | alt="croissant.jpg" |
(the file name describes nothing) |
| Storefront on the contact page | alt="Photo of the storefront" |
alt="The Blue Cup's storefront: blue awning, wooden door and the number 12" |
| Logo | alt="logo" |
alt="The Blue Cup" |
| Sign with the text "Open on Sundays" | alt="sign" |
alt="Open on Sundays" |
Guidelines for writing it:
- Don't start with "Image of…" or "Photo of…": the screen reader already announces that it's an image.
- Be concise: one or two sentences at most. If the image needs a long explanation (a complex chart), write it in the text of the page.
- It depends on the context: the same photo of the storefront could have
alt="The Blue Cup's storefront"in the gallery and analtthat highlights the step-free entrance on the contact page, where what matters is finding the premises. - If the image contains text, the
altmust include that text. - Don't repeat what the surrounding text already says.
A simple test: read the page aloud, replacing each image with its alt. If the text makes sense and no information is lost, the alt texts are good.
Decorative images and empty alt
Not all images provide information. An ornament, a wavy line or an icon next to text that already says the same thing are decorative. In those cases, the alt must be present but empty:
alt=""tells the screen reader to ignore the image: it adds nothing, and reading it out would only get in the way.- It's not the same as leaving out
alt. Without the attribute, many screen readers read out the file name ("bean dash divider dot svg"). That's whyaltmust always be there, even if it's empty.
Which alt does each image need? This table summarises the most common cases:
| Case | Example | Recommended alt |
|---|---|---|
| Informative image | Photo of a product in the gallery | A brief description of what it shows |
| Image with text | "Open on Sundays" sign | The text in the image |
| Image that is a link | Logo leading to the home page | The destination or purpose: "The Blue Cup home page" |
| Decorative image | Ornament, divider, texture | alt="" |
| Image accompanied by text that says the same thing | Phone icon next to "+34 900 000 000" | alt="" |
| Complex image | Sales chart, map | A short alt + a full explanation in the text of the page |
If you are unsure whether an image is informative or decorative, ask yourself: "If I remove the image, is any information lost?". If the answer is no, it's decorative. (In Module 8 you will see that many purely decorative images are added as backgrounds with CSS, outside the HTML.)
width and height: avoiding layout shifts
The width and height attributes state the dimensions of the image in pixels, without units:
<img src="img/storefront.jpg" alt="The Blue Cup's storefront, with a blue awning and tables on the pavement" width="800" height="600">Why are they so important? The browser reads the HTML and starts displaying the page before the images have finished downloading. If it doesn't know how much space an image will take up, it reserves 0 pixels of height for it; when the image arrives, the browser makes room for it and all the content below jumps down. It has surely happened to you: you are about to tap a link and, suddenly, it moves and you tap something else.
sequenceDiagram
participant B as Browser
participant S as Server
B->>S: Requests the HTML page
S-->>B: HTML
Note over B: Without width/height: 0 px gap<br/>With width/height: 800×600 gap reserved
B->>S: Requests img/storefront.jpg
S-->>B: Image (takes longer)
Note over B: Without width/height: the text jumps down<br/>With width/height: the image fills its gap, nothing moves
With width and height, the browser knows the image's aspect ratio from the start and reserves the exact gap. This jumping problem is called Cumulative Layout Shift (CLS) and it's one of the quality metrics used by search engines; you will come back to it in Performance and Resource Loading.
Rules for using them properly:
- Write the file's real dimensions (you can see them in the file's properties or by opening the image in the browser). If they don't match, the browser will stretch or distort it.
- Prepare images at the size at which they will be displayed: don't upload a photo 4000 pixels wide to show it at 400; it will weigh ten times as much for no benefit.
- Don't use
widthandheightto resize to a different size: that's CSS's job. With CSS (Module 8) and the techniques in Responsive Images and Videos (Module 9) you will make images adapt to each screen while keeping the aspect ratio these attributes indicate.
Image formats for the web
Not every format is suited to the same purpose. Choosing well reduces the page's weight without losing quality:
| Format | Compression | Transparency | Animation | Ideal for |
|---|---|---|---|---|
JPEG (.jpg) |
Lossy | No | No | Photographs |
PNG (.png) |
Lossless | Yes | No | Logos, screenshots, images with text or sharp edges |
GIF (.gif) |
Lossless, only 256 colours | Yes (no gradients) | Yes | Simple animations (a short video is better nowadays) |
SVG (.svg) |
Vector (not pixels) | Yes | Yes (with CSS/JS) | Logos, icons, flat illustrations: they look sharp at any size |
WebP (.webp) |
Lossy or lossless | Yes | Yes | Photos and graphics: around 25–35% lighter than JPEG/PNG |
AVIF (.avif) |
Lossy or lossless | Yes | Yes | Photos: even lighter than WebP; very widely supported in modern browsers |
Practical recommendations:
- Photos: WebP or AVIF if your tool can generate them; JPEG as the universal option.
- Logos and icons: SVG whenever you have it; otherwise, PNG.
- Avoid BMP or TIFF: they are extremely heavy and aren't designed for the web.
- Always compress images before publishing them (free tools such as Squoosh do this in the browser).
- Only use images you have the right to use: your own photos or freely licensed image libraries, respecting their terms.
Later on, in Responsive Images and Videos, you will learn how to offer the same content in several formats and sizes so that each browser can choose the best one.
Images as links
Since img is an inline element, you can put it inside an a to make the image clickable. The most typical case is the logo that takes you back to the home page, found on almost every website.
<a href="index.html"><img src="img/logo.png" alt="The Blue Cup home page" width="180" height="60"></a>Look at the alt. When the image is the only content of a link, its alt becomes the link text. That's why it shouldn't describe the drawing ("blue cup with steam") but where it leads: "The Blue Cup home page". And it can never be empty: a link with no text is announced simply as "link", or with the destination path.
If the link contains an image and text, the image becomes redundant and can have alt="":
<a href="gallery.html"><img src="img/camera-icon.svg" alt="" width="24" height="24"> See the gallery</a>alt versus title
Both attributes seem to describe the image, but they serve very different purposes:
alt |
title |
|
|---|---|---|
| What it is | An alternative to the image | Additional information (tooltip) |
| When it's seen | When the image can't be seen: screen reader, loading error | When you rest the mouse over it |
| On mobile and keyboard | Yes (screen readers read it) | Doesn't appear |
| Required? | Yes | No |
| Does it replace the other? | No | No |
<img src="img/lemon-cake.jpg" alt="Lemon sponge cake with white icing, cut into slices" width="400" height="400" title="Our baker's grandmother's recipe">Never put in title what should go in alt, and don't copy the same text into both. For most images, title is simply unnecessary. For a caption that everyone can see there is a specific element, figcaption, inside figure; you will study it in main and figure (Module 6).
Project: The Blue Cup's logo and gallery
The project's images
Save these images in the img/ folder (use your own photos, photos from a free image library or simply placeholder images of the size indicated). Notice that the names follow the conventions from File Organisation and Paths: lower case, hyphens, no accents or special characters.
| File | Dimensions | Content |
|---|---|---|
img/logo.png |
180 × 60 | Logo: a blue cup and the name |
img/storefront.jpg |
800 × 600 | The front of the premises |
img/croissant.webp |
400 × 400 | Butter croissant |
img/lemon-cake.webp |
400 × 400 | Lemon sponge cake |
img/sourdough.webp |
400 × 400 | Sourdough bread |
img/bean-divider.svg |
300 × 24 | Ornament: a row of coffee beans |
- The logo on every page
On all six pages, add the linked logo just before the menu, as the first element of the body:
<!-- Logo: goes back to the home page -->
<p class="logo"><a href="index.html"><img src="img/logo.png" alt="The Blue Cup home page" width="180" height="60"></a></p>
<!-- Main menu (in Module 6 it will go inside a nav element) -->
<ul class="menu">
<!-- … the same six links … -->
</ul>- The link with the image goes inside a
pwith the classlogo, so as not to leave loose inline content in thebody. In header, nav and footer (Module 6), the logo and menu will move into the page's semantic header. - The
altdescribes the destination, because the image is the only content of the link.
- The gallery
Replace the body of gallery.html (keeping the logo and the menu) with:
<h1>Gallery</h1>
<p>Photos, video and sounds from our café and our bakery.</p>
<h2>Our premises</h2>
<p><img src="img/storefront.jpg" alt="The Blue Cup's storefront: blue awning, wooden door and tables on the pavement" width="800" height="600"></p>
<p>You'll find us at 12 Example Street, Fictional Town. See <a href="index.html#opening-hours">our opening hours</a>.</p>
<p><img src="img/bean-divider.svg" alt="" width="300" height="24"></p>
<h2>From our bakery to your table</h2>
<ul class="product-gallery">
<li><img src="img/croissant.webp" alt="Golden, flaky butter croissant" width="400" height="400"></li>
<li><img src="img/lemon-cake.webp" alt="Lemon sponge cake with white icing, cut into slices" width="400" height="400"></li>
<li><img src="img/sourdough.webp" alt="Sourdough loaf with a floured crust and a cross-shaped score" width="400" height="400"></li>
</ul>
<p>All these products are among <a href="menu.html#specialities">our house specialities</a>.</p>Review the decisions:
- Each informative photo has a specific
alt, which describes what can be seen without starting with "photo of". - The divider is decorative:
alt="". - All the images have
widthandheightwith their real dimensions: the page won't jump while loading. - The product photos are a collection, so they are grouped in a list (
ul) with a class that will let you display them in a grid with CSS (Module 8). For now they will appear one below the other, with bullets. - The products use WebP (lightweight photos); the logo, PNG (sharp edges); the ornament, SVG.
- The storefront is 800 pixels wide and will overflow the screen on a mobile. That's normal without CSS: you will solve it in Responsive Images and Videos.
Open the gallery with Live Server and, in the Network panel of DevTools, check that all the images load with status 200 and take note of their size. Then deliberately change a path (img/storefront.jpeg) and watch the broken icon appear with the alt in its place. Change it back to the correct value.
Common Mistakes and Tips
- Leaving out
alt: the screen reader will read out the file name. Always include it, even if it's empty. - Useless
alttext: "image", "photo1", "logo.png", or starting with "Image of…". - Empty
alton an image that is the only content of a link: the link is left without a name. - Paths with capital letters or the wrong extension (
Storefront.JPGversusstorefront.jpg,.jpegversus.jpg). - Forgetting
widthandheight, or using values that don't match the real aspect ratio: layout shifts or distorted images. - Publishing huge, uncompressed photos: a photo from a mobile can weigh 5 MB; resized and in WebP, less than 100 KB.
- Using images of text (a scanned sign with the opening hours) instead of real text: it can't be searched, translated or enlarged properly. Write the text in HTML.
- Tip: decide on the
altby thinking about why the image is on that page, not just what it shows.
Exercises
Exercise 1. Write the right alt for each case and justify it:
- A photo of The Blue Cup's terrace in
news.html, in the news item announcing the opening of the terrace. - An envelope icon next to the text "[email protected]".
- An image with the text "2-for-1 on coffees on Mondays".
- A house icon, with no text, that links to
index.html.
Exercise 2. Find and correct the errors:
<img src="IMG/Seasonal Coffee.jpg">
<a href="gallery.html"><img src="img/camera-icon.svg" alt=""></a>
<img src="img/storefront.jpg" alt="Image of the storefront" width="400px" height="200px">(The storefront is 800 × 600 pixels.)
Exercise 3. In news.html, in the seasonal coffee news item, add an image img/seasonal-coffee.webp (400 × 300 pixels) showing a cup of coffee with the bag of seasonal coffee beside it. Decide whether WebP or PNG is better for this image and why.
Solutions
Solution 1.
alt="The Blue Cup's terrace with six tables under a pergola covered in plants": it's informative and conveys what the news item wants to show.alt="": the text next to it already says the same thing; the icon is decorative.alt="2-for-1 on coffees on Mondays": the image contains text, and that text is the information. (Even better would be to write the offer as HTML text.)alt="Home"(or "The Blue Cup home page"): it's the only content of a link, so thealtdescribes the destination.
Solution 2.
<img src="img/seasonal-coffee.jpg" alt="Cup of seasonal coffee on a wooden table" width="400" height="300">
<a href="gallery.html"><img src="img/camera-icon.svg" alt="Gallery" width="24" height="24"></a>
<img src="img/storefront.jpg" alt="The Blue Cup's storefront with its blue awning" width="800" height="600">- First: the folder is
imgin lower case and the file name shouldn't contain spaces or capital letters (rename it toseasonal-coffee.jpg);alt,widthandheightwere missing (400 × 300 is assumed here). - Second: the image is the only content of the link, so its
altcan't be empty. The dimensions were also missing. - Third: "Image of" is unnecessary,
widthandheightdon't takepx, and 400 × 200 doesn't match the real 4:3 aspect ratio. The real dimensions are used; the display size will be adjusted with CSS.
Solution 3.
<h3>What makes it special</h3>
<p><img src="img/seasonal-coffee.webp" alt="Cup of seasonal coffee next to its 250 g bag with the autumn label" width="400" height="300"></p>
<p>It's a coffee with gentle notes of caramel and nuts, designed to be enjoyed black, as a <i lang="it">ristretto</i>, or with milk.</p>WebP is the best option: it's a photograph, and WebP compresses it much better than PNG (which, being lossless, would produce a file several times larger). JPEG would also be acceptable.
Conclusion
You now know how to insert images with img and src, write useful alt text that conveys the image's purpose in its context, leave alt="" on decorative images, avoid layout shifts with width and height, choose between JPEG, PNG, GIF, SVG, WebP and AVIF, and use an image as a link by giving it an alt that describes its destination, without confusing alt with title. The Blue Cup now has its logo linked to the home page on every page, and the gallery shows the storefront and the bakery's star products. But an image can't capture the atmosphere of a morning in the café the way movement can. In the next lesson, Embedding Videos, you will add an introductory video with a poster image and subtitles to the gallery.
HTML Course
Module 1: Introduction to HTML
- What Is HTML?
- Setting Up Your Work Environment
- Basic Structure of an HTML Document
- Tags, Elements and Attributes
- Creating Your First HTML Page
- File Organisation and Paths
Module 2: Text Formatting in HTML
- Headings and Paragraphs
- Text Formatting Tags
- Lists: Ordered, Unordered and Description Lists
- Block Quotes and Preformatted Text
- Block and Inline Elements: div and span
Module 3: Links and Media in HTML
- Creating Hyperlinks
- Special Links: Anchors, Email, Phone and Downloads
- Adding Images
- Embedding Videos
- Using the Audio Element
Module 4: Tables in HTML
- Basic Table Structure
- Table Head, Body and Foot
- Merging Cells: colspan and rowspan
- Accessible Tables: caption, scope and headers
- Styling Tables
Module 5: Forms in HTML
- Creating a Basic Form
- Form Elements: input, textarea and select
- HTML5 Input Types
- Labels and Grouping: label, fieldset, legend and datalist
- Form Attributes and Validation
- Submitting Forms
Module 6: HTML5 Semantic Elements
- Introduction to Semantic HTML
- header, nav and footer
- article, section and aside
- main and figure
- Other Semantic Elements: time, address, details and dialog
Module 7: Advanced HTML Techniques
- HTML Entities
- Using iframes
- Data Attributes
- Metadata: meta, SEO and Open Graph
- Microdata and Structured Data
- Graphics in HTML: SVG and canvas
Module 8: Integrating HTML and CSS
- Linking CSS to HTML
- Inline, Internal and External CSS
- Basic CSS Selectors
- The Box Model
- Styling HTML Elements
- Introduction to Layout with Flexbox and Grid
Module 9: Responsive Web Design
Module 10: Best Practices and Accessibility
- HTML Best Practices
- Validating HTML Code
- Web Accessibility Basics
- Using ARIA Roles and Attributes
- Accessibility Testing
- Performance and Resource Loading
