Lesson 8 +10 XP

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 lives
  • alt: alternative text, a description of the picture
Code

html
<img src="cat.jpg" alt="A fluffy cat sleeping">

&lt;img&gt; has no closing tag! It's a &quot;self-closing&quot; 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=&quot;A red bicycle parked by a tree&quot;.

width and height

Set the size of the image. This also stops the page from jumping around while the image loads.

Code

html
<img src="dog.jpg" alt="A happy dog" width="300" height="200">

Figures: &lt;figure&gt; and &lt;figcaption&gt;

Wrap an image with a caption in &lt;figure&gt;, and add &lt;figcaption&gt; for the caption text.

Code

html
<figure>
  <img src="cake.jpg" alt="A chocolate cake">
  <figcaption>Our famous birthday cake</figcaption>
</figure>

Picture element: &lt;picture&gt;

&lt;picture&gt; lets you show different images on different screens. It has &lt;source&gt; children plus one &lt;img&gt; at the end as a backup.

Code

html
<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!

Code

html
<img
  src="photo.jpg"
  srcset="photo-small.jpg 480w, photo-large.jpg 1080w"
  alt="A sunset at the beach">

Lazy loading: loading

loading=&quot;lazy&quot; makes the browser wait to load pictures that are off-screen. It saves data and makes pages faster!

Code

html
<img src="below-fold.jpg" alt="Far down the page" loading="lazy">

TL;DR

  • &lt;img src=&quot;...&quot; alt=&quot;...&quot;&gt; shows a picture (no closing tag!).
  • Always write a good alt description.
  • &lt;figure&gt; + &lt;figcaption&gt; add a caption.
  • &lt;picture&gt;/&lt;source&gt;/srcset serve the right size image.
  • loading=&quot;lazy&quot; loads off-screen images only when needed.