-1

I want to give image height to image main div to make it fit inside div like below is image which height is 186px so i want to give that image height to main div to make them fit. Is there any want to get image height which i mark in below image.

enter image description here

As there is a solution but that is working fine as it giving another height.

 var img = new Image();
 img.src = this.props.image;
 console.log(img.height) // it give me 406 not 186

This is what is my problem and what i want. enter image description here

Ahsan Ullah
  • 158
  • 4
  • 15

1 Answers1

0

Yeah,you can get image height by accessing img.naturalHeight ,same goes for width as well but u have to wait for browser to download image (use onload event and access once image loaded) .u can find aspect ratio and make your div responsive or apply it's original width and height. Happy coding.

sudhakar selva
  • 387
  • 4
  • 16
  • but it give same **406** pixel not **186**. `async componentDidMount() { var img = new Image(); img.src = this.props.image; img.onload = async () => { console.log("image is loaded",img.naturalHeight); } }` – Ahsan Ullah Nov 06 '20 at 18:58
  • 1
    To be sure, select img tag in dev tools elements tab and move to console then type $0.naturalHeight ,then that's the image actual height – sudhakar selva Nov 06 '20 at 19:04
  • It giving me 406 but then what is that **186**. how to get that please help me – Ahsan Ullah Nov 06 '20 at 19:07
  • 1
    If u didn't set height ,then browser automatically sets height 186 – sudhakar selva Nov 06 '20 at 19:10
  • But it not giving it 186 and it make it center. let me add those image in my question. – Ahsan Ullah Nov 06 '20 at 19:11
  • Okay,try giving some fixed width and height and inspect it in elements tab. – sudhakar selva Nov 06 '20 at 19:16
  • 1
    Original image size is 722*406px, which is tried to contain inside 322px width so browser squeezed its size to preserve aspect ratio , in css, u can give object-fit: cover.which stops browser reducing image height. Use https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css this link as reference, – sudhakar selva Nov 06 '20 at 19:25