How to maintain aspect ratio using HTML IMG tag

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" />

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)