How TO – Responsive Images
Learn how to create an responsive image with CSS.
Responsive images will automatically adjust to fit the size of the screen.
Resize the browser window to see the responsive effect:
How To Create Responsive Images
Step 1) Add HTML:
Example
<img src=”nature.jpg” alt=”Nature” class=”responsive”>
Step 2) Add CSS:
If you want the image to scale both up and down on responsiveness, set the CSS width property to 100% and height to auto:
Example
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<style>
.responsive {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<h2>Responsive Images</h2>
<p>If you want the image to scale both up and down on responsiveness, set the CSS width property to 100% and height to auto.</p>
<p>Resize the browser window to see the effect.</p>
<img src=”img_nature.jpg” alt=”Nature” width=”600″ height=”400″>
</body>
</html>
If you want an image to scale down if it has to, but never scale up to be larger than its original size, use max-width: 100%:
Example
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<style>
.responsive {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<h2>Responsive Images</h2>
<p>If you want an image to scale down if it has to, but never scale up to be larger than its original size, use max-width: 100%.</p>
<p>Resize the browser window to see the effect.</p>
<img src=”img_nature.jpg” alt=”Nature” width=”600″ height=”400″>
</body>
</html>
If you want to restrict a responsive image to a maximum size, use the max-width property, with a pixel value of your choice:
Example
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<style>
.responsive {
width: 100%;
max-width: 400px;
height: auto;
}
</style>
</head>
<body>
<h2>Responsive Images</h2>
<p>If you want to restrict a responsive image to a maximum size, use the max-width property, with a pixel value of your choice.</p>
<p>Resize the browser window to see the effect.</p>
<img src=”img_nature.jpg” alt=”Nature” width=”600″ height=”400″>
</body>
</html>