Menu
Coddy logo textTech

Flexible Images

Part of the Styling with CSS section of Coddy's HTML journey — lesson 66 of 76.

In responsive web design, flexible images automatically adjust to fit different screen sizes, ensuring they look good on all devices. Without flexibility, images may be too large on small screens or break the layout.

How to Make Images Flexible:

1.Use CSS max-width
Setting max-width: 100% ensures that images never exceed their container width.

img {
  max-width: 100%;
  height: auto; /* Maintains aspect ratio */
}

2.Use Viewport Units
You can size images using vw (viewport width) to make them scale with the screen size.

img {
  width: 50vw; /* Image takes up 50% of viewport width */
}
challenge icon

Challenge

Easy

You are given an HTML document with an image. Your task is to make the image responsive so it adjusts to different screen sizes.

  1. Write a CSS rule that targets all the elements with class img-max. Set its max-width to 100% and its height to auto.
  2. Write a CSS rule that targets all the elements with class img-vw. Set its width to 50vw and its height to auto.

Cheat sheet

Flexible images automatically adjust to fit different screen sizes in responsive web design.

Using max-width:

img {
  max-width: 100%;
  height: auto; /* Maintains aspect ratio */
}

Using viewport units:

img {
  width: 50vw; /* Image takes up 50% of viewport width */
}

Try it yourself

<html>
<head>
    <title>Flexible Images</title>
    <style>
        /* Write CSS rules here */
    </style>
</head>
<body style="background-color:lightblue">
     <div class="container">
        <h2>Image with max-width: 100%</h2>
        <img class="img-max" src="https://upload.wikimedia.org/wikipedia/commons/0/0e/Adelie_penguins_in_the_South_Shetland_Islands.jpg" alt="Max-Width Image">
    </div>

    <div class="container">
        <h2>Image with width: 50vw</h2>
        <img class="img-vw" src="https://upload.wikimedia.org/wikipedia/commons/4/40/Adelie_Penguins_on_iceberg.jpg">
    </div>
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Styling with CSS