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
EasyYou are given an HTML document with an image. Your task is to make the image responsive so it adjusts to different screen sizes.
- Write a CSS rule that targets all the elements with class
img-max. Set itsmax-widthto100%and itsheighttoauto. - Write a CSS rule that targets all the elements with class
img-vw. Set itswidthto50vwand itsheighttoauto.
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>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Styling with CSS
5 Colors and Backgrounds
Background ColorHEX ColorsRGB ColorsTransparency with RGBARecap Challenge #13Basic Selectors
Introduction to SelectorsType SelectorClass SelectorID SelectorGroup SelectorsUniversal SelectorSelection Challenge9Flex Box
What is a Flex Box?Flex DirectionJustify ContentAlign ItemsThe Perfect CenterFlex Box Challenge12Responsive Design Basics
What is Responsive Design?Viewport Meta TagFluid LayoutsViewport UnitsMedia Queries BasicsFlexible Images