css image keep ratio code example

Example 1: keep aspect ratio of image css

img {
    display: block;
    max-width: 100%;
    max-height: 100%;
    width: auto;
    height: auto;
}

Example 2: css keep image ratio

img {
  object-fit: cover;
  width: 100px;
  height:100px;
}

Example 3: preserve aspect ratio image css

/* Simply add width without height,
aspect ratio will be maintained 
and height will be calculated accordingly*/

img {
  width: 100px;
}

Example 4: html image keep aspect ratio

Don't set height AND width. Use one or the other and the correct aspect ratio will be maintained.

Tags:

Css Example