Home > Software design >  Image width and height
Image width and height

Time:02-28

Why does the height of an image also change in CSS when I only change the width. I changed the width of an image using the following code:

img{
width: 25%;
}

And it not only made the width change but also the height of the image.

CodePudding user response:

the object size is calculated on its given values. when you only define the width, then the missing height value is determined by its given aspect ratio.

further read:

If the specified size defines only the width or only the height, the missing value is determined using the intrinsic ratio, if there is any, the intrinsic dimensions if the specified value matches, or the default object size for that missing value

https://developer.mozilla.org/en-US/docs/Web/CSS/image

CodePudding user response:

This is done to preserve the aspect ratio while resizing images. when you are specifying the width to 25% the height is set to auto.

img {
  width: 100%;
  height: auto;
}

You can specify both the height and width explicitly but that sometime causes it to lose its aspect ratio and responsiveness for different available widths. Therefore the image won't look as it was intended to be.

Note: You can do the opposite set width as auto, but most layouts are generally width constrained and not height.

CodePudding user response:

If you want avoid this behavior you must apply a fix height to the image. like that:

const bt = document.querySelector('button');
let i = 10;
bt.addEventListener('click', function() {
  const img  = document.querySelector('img');  
  img.style.width = i   "%"; 
  i  ;  
});
img {
  height:200px;
}
<button>increase by 1%</button>
<div>
  <img src="https://via.placeholder.com/200">
</div>

  •  Tags:  
  • css
  • Related