Getting and setting image width with jQuery based on their original size

You may be developing a website where a gallery or portfolio application of photos that will be uploaded in various sizes. Creating responsive CSS for images we typically set a width of 100% and then add a max-width of a specific size such as 1900 pixels to allow scaling for mobile devices. However if your image is below 1900 pixels wide, lets say at 1000 pixels wide, you’ll get an upscale to 1900 pixels wide creating a non-pixel perfect blurry image. A solution if needed with jQuery is to use JavaScript’s ability to get the original images size and auto apply it to the image with a max-width of whatever that image size is. Below is an example of code on how to do so within a a container with a class name of “photos”.

HTML


jQuery

As you can see by code this will get all images within the container using jQuery’s “each” loop and apply their max-width size as an inline style on each image. Of course you’ll need your CSS setup like below as example max-width 1900 pixels. I chose this size since I only develop websites to max fit standard HD resolution. Notice its 1900 not 1920 to allow for 10 pixels of padding on left and right sides of the container(“photos”) or your body tag for mobile:

CSS

Tip
Your image will abruptly change size after loading, that’s why its best to set an opacity on them at “0” and once the page is loaded add the opacity of “1”. You can animate a fade in with jQuery or even take it a step further and add a loader per image. Typically if your building a web photo application these are things you would do.

Author: Mark Hawkins

Sr. Graphic Designer, Web Developer and Animator fueled by passion for design, development and some RockStar energy drinks.

Leave a Reply

Your email address will not be published. Required fields are marked *