Skip to content

Instantly share code, notes, and snippets.

@AllThingsSmitty
Last active October 7, 2021 16:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AllThingsSmitty/e36264b46d509e7d76b7 to your computer and use it in GitHub Desktop.
Save AllThingsSmitty/e36264b46d509e7d76b7 to your computer and use it in GitHub Desktop.
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