Don’t set height AND width. Use one or the other and the correct aspect ratio will be maintained.
.widthSet {
max-width: 64px;
}
.heightSet {
max-height: 64px;
}
<img src="https://placeimg.com/200/500/any/grayscale" />
<img src="https://placeimg.com/200/500/any/grayscale" width="64" />
<img src="https://placeimg.com/200/500/any/grayscale" height="64" />
<img src="https://placeimg.com/200/500/any/grayscale" class="widthSet" />
<img src="https://placeimg.com/200/500/any/grayscale" class="heightSet" />
Another option that gives you more flexibility is to use object-fit
. This allows fixed dimensions to be set for the img
whilst the image itself can be presented in a number of different ways within the defined area.
img {
width: 128px;
height: 128px;
border: 1px solid hotpink;
}
.fill {
object-fit: fill;
}
.contain {
object-fit: contain;
}
.cover {
object-fit: cover;
}
.scale-down {
object-fit: scale-down;
}
<img src="https://placeimg.com/200/500/any/grayscale" class="fill" />
<img src="https://placeimg.com/200/500/any/grayscale" class="contain" />
<img src="https://placeimg.com/200/500/any/grayscale" class="cover" />
<img src="https://placeimg.com/200/500/any/grayscale" class="scale-down" />