HTML Images
HTML images are added with the <img> element. It is a void element with two essential attributes: src, the image address, and alt, a text description of the image.
Adding an Image
Setting width and height lets the browser reserve space before the image loads, which stops the page from jumping around.
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Image</title></head>
<body>
<img src="https://picsum.photos/id/1043/400/250" alt="Mountain lake at sunrise" width="400" height="250">
</body>
</html>Writing Good alt Text
- Describe what the image shows and why it matters in context
- Keep it short, usually one sentence
- Do not start with "image of"; screen readers already say it is an image
- Use alt="" for purely decorative images so they are skipped
Lazy Loading Images
Add loading="lazy" so images below the fold only download when the user scrolls near them. This speeds up the first page load.
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Lazy</title></head>
<body>
<p>Scroll down.</p>
<div style="height:1200px"></div>
<img src="https://picsum.photos/id/1025/300/200" alt="A pug wrapped in a blanket" width="300" height="200" loading="lazy">
</body>
</html>Responsive Images and Captions
srcset offers several sizes and the browser picks the best one for the screen. <figure> and <figcaption> attach a visible caption to an image.
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Responsive</title>
<style>img { max-width: 100%; height: auto; }</style></head>
<body>
<figure>
<img src="https://picsum.photos/id/1039/800/400"
srcset="https://picsum.photos/id/1039/400/200 400w, https://picsum.photos/id/1039/800/400 800w"
sizes="(max-width: 600px) 400px, 800px"
alt="Waterfall in a forest" width="800" height="400">
<figcaption>A waterfall photographed in early spring.</figcaption>
</figure>
</body>
</html>Image Formats
Use JPEG or WebP/AVIF for photos, PNG for images that need sharp edges or transparency, and SVG for logos and icons that must stay crisp at any size. Modern formats like WebP and AVIF are much smaller and are supported by all current browsers.
Frequently asked questions
How do I resize an image in HTML?
Use the width and height attributes, or CSS such as img { max-width: 100%; height: auto; } for images that scale with the screen.
Why is my HTML image not showing?
Usually the src path is wrong, the file name has a different case, or the extension does not match. Check the path relative to your HTML file and look for errors in the browser console.
How do I center an image in HTML?
Make it a block and use auto margins in CSS: img { display: block; margin: 0 auto; }.