Learn how to build and design websites with our tutorials.

Responsive Images Tutorial

View Tutorial Contents


How To Make Images Responsive

When making websites, you want the layout of the website responsive. Part of making responsive websites that work as they should is making the images within them responsive as well. The reason for this is so that the layout does not break as it is scaled down.

Responsive websites are made up of content blocks, for example, <div>s, <header>s, <footer>s, etc. These content blocks should be scalable so that they can fit within the web browser window when it is resized. Any content that is within these content blocks, including images, should be scalable as well so that when the content blocks are scaled down, the content within those content blocks are not bigger than the content block itself. If the width and/or height of content within these content blocks is bigger than the content block that contains it, the layout will probably break at some point.

The issue with images as they relate to responsive website design is that they typically have a fixed width and height.

How To Make An Image Responsive

The simplest and best way to make images responsive is to apply the max-width property with a value of 100% and the height property with a value of auto to your images.

Applying the max-width property with a value of 100% will ensure that the width of the image is never more than the width of its containing block element.

Applying the height property with a value of auto will ensure that the image's original aspect ratio is preserved.

The code example below shows you how to apply the max-width and height properties to an image to make it responsive.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>

img{
max-width: 100%;
height: auto;
border: none;
}

</style>

</head>
<body>

<figure>
<figcaption>This is another random image.</figcaption>
<img src="circle.png" alt="This is an image" />
</figure>

</body>
</html> 

responsive image

Different Images at Different Screen Sizes using CSS

Sometimes you may want to use different background images based on different screen sizes. The CSS @media queries are used to do this.

The code example below shows you how to apply different images based on different screen sizes.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8" />
<title>Your Page Title</title>
<style>

#header-wrap{
width: 100%;
height: 100px;
margin: 0;
padding: 0;
background: url('images/large-background-image.jpg');
}
@media all and (max-width: 900px){
	#header-wrap{
		background: url('images/medium-background-image.jpg');
	}
}
@media all and (max-width: 600px){
	#header-wrap{
		background: url('images/small-background-image.jpg');
	}
}

</style>

</head>
<body>

<header id="header-wrap">

<p>
This is some content.
</p>

</header>

</body>
</html>