Loading lessons...
Images
Images
Pictures make the web colorful. HTML shows them with the <img> tag.
The <img> tag
<img> needs two things:
src: the source, where the picture livesalt: alternative text, a description of the picture
<img src="cat.jpg" alt="A fluffy cat sleeping">
<img> has no closing tag! It's a "self-closing" tag.
Why alt matters
alt shows up when:
- The picture can't load.
- A screen reader reads your page to someone who can't see.
Describe the picture simply: alt="A red bicycle parked by a tree".
width and height
Set the size of the image. This also stops the page from jumping around while the image loads.
<img src="dog.jpg" alt="A happy dog" width="300" height="200">
Figures: <figure> and <figcaption>
Wrap an image with a caption in <figure>, and add <figcaption> for the caption text.
<figure>
<img src="cake.jpg" alt="A chocolate cake">
<figcaption>Our famous birthday cake</figcaption>
</figure>
Picture element: <picture>
<picture> lets you show different images on different screens. It has <source> children plus one <img> at the end as a backup.
<picture>
<source media="(min-width: 800px)" srcset="wide.jpg">
<source media="(min-width: 400px)" srcset="medium.jpg">
<img src="small.jpg" alt="A mountain view">
</picture>
Responsive images: srcset
srcset tells the browser several image sizes, and the browser picks the best one for the screen. This makes pages load faster on phones!
<img
src="photo.jpg"
srcset="photo-small.jpg 480w, photo-large.jpg 1080w"
alt="A sunset at the beach">
Lazy loading: loading
loading="lazy" makes the browser wait to load pictures that are off-screen. It saves data and makes pages faster!
<img src="below-fold.jpg" alt="Far down the page" loading="lazy">
TL;DR
<img src="..." alt="...">shows a picture (no closing tag!).- Always write a good
altdescription. <figure>+<figcaption>add a caption.<picture>/<source>/srcsetserve the right size image.loading="lazy"loads off-screen images only when needed.