🤯 50% Off! 700+ courses, assessments, and books

HTML5 Responsive Design: How to Determine the Real Dimensions of an Image in JavaScript

Craig Buckler

Responsive design is one of the most useful web techniques to appear during the past few years. A website layout can adapt to a device’s screen and look beautiful no matter what resolution is used.

Responsive images are normally coded without width and height attributes, e.g.

<img id="myimage" src="myimage.jpg" alt="my image" />

The image will size itself and we can add a little CSS to ensure an image cannot exceed its real dimensions.

	max-width: 100%;

It’s often necessary to manipulate these scaled images in JavaScript; perhaps for a game, lightbox or animation effect. In those situations, you need to determine the image’s real height and width. However, the width and height properties return the current (resized) dimensions:

var myimage = document.getElementById("myimage");
var w = myimage.width;	// current width, e.g. 400px
var h = myimage.height;	// current height, e.g. 300px

Fortunately, the modern HTML5 browsers provide two further properties:

var rw = myimage.naturalWidth;	// real image width
var rh = myimage.naturalHeight;	// real image height

The properties are supported in IE9, Firefox, Chrome, Safari and Opera. Note the image must be fully downloaded before the dimensions are available. To ensure it’s ready, you can either attach a “load” event to the window or the image itself or check the image’s .complete property before testing the dimensions.

IE6, 7 and 8

.naturalWidth and .naturalHeight are not supported in the older editions of Internet Explorer. We can still determine the real dimensions by loading the image into an in-memory object and examining the standard width and height properties, e.g.

var myimage = document.getElementById("myimage");

if (typeof myimage.naturalWidth == "undefined") {
	// IE 6/7/8
	var i = new Image();
	i.src = myimage.src;
	var rw = i.width;
	var rh = i.height;
else {
	// HTML5 browsers
	var rw = myimage.naturalWidth;
	var rh = myimage.naturalHeight;

I’m continually amazed to discover these new properties and methods; they make our lives a little easier.

CSS Master, 3rd Edition