Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Every possible way (pretty much) to get the dimensions of any image on a web page with JavaScript
var myImg = document.querySelector('img'),
op = document.querySelector('output');
op.innerHTML = "Computed width: " +
getComputedStyle(myImg).getPropertyValue('width') +
'<br>' + 'img.width: ' +
myImg.width +
'<br>' + 'getAttribute(width): ' +
myImg.getAttribute('width') +
'<br>' + 'img.naturalWidth: ' +
myImg.naturalWidth;
// Credit: Louis Lazarus
// How this works:
// The `getComputedStyle()` method lets you get any property value, and this is the final computed style, whether it's in the CSS or not. Note that if I used ems or another unit, it would still spit out the value in pixels.
// The second method is just accessing the width property of the image directly, which basically gets the same result, but without the unit. Again, this is the computed width, not the original or that in the HTML.
// The `getAttribute()` method allows you to get exactly what's in the HTML. This was overridden in our CSS, but we can access it here.
// Finally, we have probably the least-known technique, using the `naturalWidth` property. This gets the original width of the element, regardless of what's in the HTML or the CSS. There's also the complementary `naturalHeight` to go along with that.
img {
display: block;
margin: 10px auto;
height: 449px;
width: 299px;
}
output {
display: block;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
line-height: 1.5;
text-align: center;
}
<img src="https://placekitten.com/g/400/600" width="300" height="450">
<output></output>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment