sunil kumar
sunil kumar

Reputation: 2303

How to maintain aspect ratio using HTML IMG tag

I am using an img tag of HTML to show a photo in our application. I have set both its height and width attribute to 64. I need to show any image resolution (e.g. 256x256, 1024x768, 500x400, 205x246, etc.) as 64x64. But by setting the height and width attributes of an img tag to 64, it's not maintaining the aspect ratio, so the image looks distorted.

For your reference my exact code is:

<img src="Runtime Path to photo" border="1" height="64" width="64">

Upvotes: 219

Views: 393605

Answers (18)

Douglas Gross
Douglas Gross

Reputation: 1

I must say, in my career of web deving it has historically been a pain, especially when they change things over and over and expect it all to be properly supported. However, this is what I had to do to keep images from being condensed.

  div.main img {
    max-width: 100%;
    object-fit: contain;
    block-size: auto;
  }

Upvotes: -1

ShellDude
ShellDude

Reputation: 606

I was taught to do this differently.

This pre-fills the container with whatever you want at the right dimensions prior to the image being rendered. In this use case, assume our aspect ratio is 16:9 (56.25%):

const myTimeout = setTimeout(loadImage, 5000);

function loadImage() {
  myImg.src = "https://upload.wikimedia.org/wikipedia/commons/f/f8/Aspect-ratio-16x9.svg"
}
.webcam {
  display: block;
  position: relative;
  height: 0;
  padding-bottom: 56.25%
}

.webcam img {
  border-radius: 5px;
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%!important;
  height: 100%!important;
}
<html>
<head/>

<body>
  I am above the image<br/>
  <div style="display: block; width: 200px; border: 1px; background: green;">
    <div class="webcam">
      <img id="myImg" />
    </div>
  </div>
    I am below the image
</body>

</html>

Upvotes: 0

Gatis Negribs
Gatis Negribs

Reputation: 21

Best practice would be to use fixed "width" and "height" atributes for img tag, because browser should know how much place should be reserved for image before loading it to avoid layout flickering during loading period. Just need to override one of this in CSS to "auto"

img {
  height: auto;
}
<img src="/sample.jpg" width="200" height="166">

Upvotes: 0

Turnip
Turnip

Reputation: 36632

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;
}

.none {
  /* Image is not scaled */ 
  object-fit: none;
}

.fill {
  /* Image is scaled to fill the container. */
  /* Aspect ratio IS NOT maintained */
  object-fit: fill;
}

.cover {
  /* Image is scaled to fill the container. */
  /* Aspect ratio IS maintained */
  object-fit: cover;
}

.contain {
  /* Image is scaled to fit within the container. */
  /* Aspect ratio IS maintained */
  object-fit: contain;
}

.scale-down {
  /* Uses either 'none' or 'contain' to produce the smallest image size */
  object-fit: scale-down;
}
<img src="https://picsum.photos/seed/stackoverflow/200/300" class="none" />

<img src="https://picsum.photos/seed/stackoverflow/200/300" class="fill" />

<img src="https://picsum.photos/seed/stackoverflow/200/300" class="cover" />

<img src="https://picsum.photos/seed/stackoverflow/200/300" class="contain" />

<img src="https://picsum.photos/seed/stackoverflow/200/300" class="scale-down" />

Upvotes: 197

kennarddh
kennarddh

Reputation: 2665

You can set aspect ratio

img {
  width: 64px;
  aspect-ratio: 1/1;
}
<img src="Runtime Path to photo" border="1">

Upvotes: 1

AlexElin
AlexElin

Reputation: 1568

There's a new CSS property aspect-ratio. It sets a preferred aspect ratio for the box, which will be used in the calculation of auto sizes and some other layout functions.

img {
  width: 100%;
  aspect-ratio: 16/9;
}

It's supported in all well spread browsers.
MDN link: https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio
And https://web.dev/aspect-ratio/ contains good examples of using this property

Upvotes: 27

Juliano
Juliano

Reputation: 2552

You need a div to wrap your image to have a consistente aspect ratio.

You can use the padding-bottom trick to force the div to respect an aspect ratio and a absolute positioned image to fill the space.

The image will be also responsive, taking all the horizontal space available.

.img-frame{
  width: 100%;
  padding-bottom: 100%;
  background: gray;
  overflow: hidden;
  position: relative;
}

.img-frame-4by3{
  padding-bottom: 75%;
}

.img-frame-16by9{
  padding-bottom: 56.25%;
}


.img-frame-5by1{
  padding-bottom: 20%;
}


.img-frame img{
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div style="max-width:100px; margin: 1rem auto;">
  
  <p>4:3</p>
  <div class="img-frame img-frame-4by3">
    <img src="http://placekitten.com/g/400/400" />
  </div>
  
  <br />
  
  <p>16:9</p>
  <div class="img-frame img-frame-16by9">
    <img src="http://placekitten.com/g/400/400" />
  </div>
  
  <br />
  
  <p>5:1</p>
  <div class="img-frame img-frame-5by1">
    <img src="http://placekitten.com/g/400/400" />
  </div>
  
</div>

Upvotes: 2

Kevin Taing
Kevin Taing

Reputation: 61

My site displays a number of photos (with a variety of aspect ratios) and clicking one opens it in a modal. To get it to fit into the modal without cropping, scrolling, or distortion I used the following class on my img tag

.img {
  max-height: 100%;
  max-width: 100%;
  object-fit: scale-down;
}

Upvotes: 2

Stokely
Stokely

Reputation: 15759

The poster is showing a dimension constrained by height in most cases he posted >>> (256x256, 1024x768, 500x400, 205x246, etc.) but fitting a 64px max height pixel dimension, typical of most landscape "photos". So my guess is he wants an image that is always 64 pixels in height. To achieve that, do the following:

<img id="photo1" style="height:64px;width:auto;" src="photo.jpg" height="64" />

This solution guarantees the images are all 64 pixels max in height and allows width to extend or shrink based on each image's aspect ratio. Setting height to 64 in the img height attribute reserves a space in the browser's Rendertree layout as images download, so the content doesn't shift waiting for images to download. Also, the new HTML5 standard does not always honor width and height attributes. They are dimensional "hints" only, not final dimensions of the image. If in your style sheet you reset or change the image height and width, the actual values in the images attributes get reset to either your CSS value or the images native default dimensions. Setting the CSS height to "64px" and the width to "auto" forces width to start with the native image width (not image attribute width) and then calculate a new aspect-ratio using the CSS style for height. That gets you a new width. So the height and width "img" attributes are really not needed here and just force the browser to do extra calculations.

Upvotes: 0

With css:

.img {
    display:table-cell;
    max-width:...px;
    max-height:...px;
    width:100%;
}

Upvotes: 0

Ankit Kumar Verma
Ankit Kumar Verma

Reputation: 435

Use object-fit: contain in css of html element img.

ex:

img {
    ...
    object-fit: contain
    ...
}

Upvotes: 26

Nick friesen
Nick friesen

Reputation: 31

Try this:

<img src="Runtime Path to photo" border="1" height="64" width="64" object-fit="cover">

Adding object-fit="cover" will force the image to take up the space without losing the aspect ratio.

Upvotes: 3

Lucio Fonseca
Lucio Fonseca

Reputation: 3527

<img src="Runtime Path to photo"
     style="border: 1px solid #000; max-width:64px; max-height:64px;">

Upvotes: 47

AKHIL P
AKHIL P

Reputation: 1311

here is the sample one

div{
   width: 200px;
   height:200px;
   border:solid
 }

img{
    width: 100%;
    height: 100%;
    object-fit: contain;
    }
<div>
  <img src="https://upload.wikimedia.org/wikipedia/meta/0/08/Wikipedia-logo-v2_1x.png">
</div>

Upvotes: 108

Anonymous Coward
Anonymous Coward

Reputation: 141

None of the methods listed scale the image to the largest possible size that fits in a box while retaining the desired aspect ratio.

This cannot be done with the IMG tag (at least not without a bit of JavaScript), but it can be done as follows:

 <div style="background:center no-repeat url(...);background-size:contain;width:...;height:..."></div>

Upvotes: 14

Ilya Streltsyn
Ilya Streltsyn

Reputation: 13526

Set width and height of the images to auto, but limit both max-width and max-height:

img {
    max-width:64px;
    max-height:64px;
    width:auto;
    height:auto;
}

Fiddle

If you want to display images of arbitrary size in the 64x64px "frames", you can use inline-block wrappers and positioning for them, like in this fiddle.

Upvotes: 58

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Wrap the image in a div with dimensions 64x64 and set width: inherit to the image:

<div style="width: 64px; height: 64px;">
    <img src="Runtime path" style="width: inherit" />
</div>

Upvotes: 8

Sahan De Silva
Sahan De Silva

Reputation: 471

Why don't you use a separate CSS file to maintain the height and the width of the image you want to display? In that way, you can provide the width and height necessarily.

eg:

       image {
       width: 64px;
       height: 64px;
       }

Upvotes: 1

Related Questions