Getting the width and height of an Image

So I have a element and I want to get the image’s height and width property, however this is my css:

let h = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('height').replace('px',''));
let w = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('width').replace('px',''));
    z-index: 0;
    display: block;
    top: 0px;
    margin-left: auto;
    margin-right: auto;

    max-height: 100%;
    max-width: 100%;

    position: absolute;
    align-self: center;

    margin: auto;
    left: 0;
    right: 0;
<img src="src.jpg" id="image">

as you can see i didn’t set a height and width property because I don’t want the image to have a fixed width and height, so someone introduced me to use:


and so I did, but it is not accurate from my experience:


let h = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('height').replace('px',''))
let w = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('width').replace('px',''))

here is the screenshot of the results it logged:

and here is the screenshot of the actual width and height of the element:

as you can see the image is 670 x 514 but it logged 459 as its height, anyone can help me with this problem?

1 thought on “Getting the width and height of an Image”

  1. This should help

    The problem is that your image need to be loaded first.

    const img = document.getElementById("img");
    if(img.complete) {
       console.log(img.width, img.height)
    } else {
      img.addEventListener('load', function() {
            const imageWidthRendered = this.width;
            const imageHeightRendered = this.height;
        console.log(imageWidthRendered, imageHeightRendered)
    <img id="img" src="">

Leave a Comment