By utilizing the methods below, you can easily adjust the size of images to fit their parent container, making it easy to scale up or down based on the width.
All images are contained within a fixed-width parent element for demonstration purposes, which would match the actual width in a live environment.
Effective Approach (2018):
This technique instructs the browser to display the image at its maximum available width while automatically adjusting the height proportionally.
.parent {
width: 100px;
}
img {
display: block;
width: 100%;
height: auto;
}
<p>Original dimensions of this image are 400x400 pixels, but CSS will resize it accordingly:</p>
<div class="parent">
<img width="400" height="400" src="https://place-hold.it/400x400">
</div>
Innovative Solution:
This advanced option allows for cropping images regardless of their original size and includes adding a background color to fill any gaps created by the crop.
.parent {
width: 100px;
}
.container {
display: block;
width: 100%;
height: auto;
position: relative;
overflow: hidden;
padding: 34.37% 0 0 0; /* 34.37% = 100 / (w / h) = 100 / (640 / 220) */
}
.container img {
display: block;
max-width: 100%;
max-height: 100%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<p>The image originally measures 640x220 pixels, but with CSS adjustments:</p>
<div class="parent">
<div class="container">
<img width="640" height="220" src="https://place-hold.it/640x220">
</div>
</div>
To determine the top padding percentage, calculate the image's aspect ratio like so:
640px (w) = 100%
220px (h) = ?
640/220 = 2.909
100/2.909 = 34.37%
Hence, the top padding should be set to 34.37%.