Tsallaka zuwa abun ciki
Justice Tech School

Responsive Images

Set max-width: 100% and height: auto in CSS so an image never overflows its container. Use the width attribute for the natural size.

The picture element lets the browser choose between several files, and srcset offers different sizes. Always keep a normal img inside as the fallback.

Example
<style>img { max-width: 100%; height: auto; }</style>
<img alt="Green banner" width="600" src="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%27600%27 height=%27120%27%3E%3Crect width=%27600%27 height=%27120%27 fill=%27%23166534%27/%3E%3C/svg%3E">

The picture element

Example
<picture>
  <source media="(min-width: 800px)" srcset="large.jpg">
  <img src="small.jpg" alt="A description">
</picture>

Exercise

Stop the image overflowing its container.

img { max-width: ; height: auto; }

Quiz Test

Which element lets the browser pick between several image files?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.