Q:

How to Auto-resize an Image to Fit into a DIV Container using CSS

0

How to Auto-resize an Image to Fit into a DIV Container using CSS

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the CSS max-width Property

You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.

Additionally, you can also apply the max-height property if you've a fixed height div element, so that the image doesn't overflow from the div's boundary horizontally or vertically.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Resize Image Proportionally with CSS</title>
<style>
    img{
        max-width: 100%;
        max-height: 100%;
        display: block; /* remove extra space below image */
    }
    .box{
        width: 250px;        
        border: 5px solid black;
    }    
    .box.large{
        height: 300px;
    }
    .box.small{
        height: 100px;
    }
</style>
</head>
<body>
    <h2>Image inside Auto-height Div</h2>
    <div class="box">
        <img src="examples/images/sky.jpg" alt="Cloudy Sky">
    </div>
    <br>
    <h2>Image inside Portrait Div</h2>
    <div class="box large">
        <img src="examples/images/sky.jpg" alt="Cloudy Sky">
    </div>
    <br>
    <h2>Image inside Landscape Div</h2>
    <div class="box small">
        <img src="examples/images/sky.jpg" alt="Cloudy Sky">
    </div>
    <p><strong>Note:</strong> The original size of the image is 500x300 pixels, but using the "max-width" and "max-height" property we are still able to show the complete image inside the DIVs having different width.</p>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

HTML / CSS Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Overlay One DIV Over Another DIV using CSS... >>
<< How to Change the Color of an hr Element using CSS...