Tuesday, September 18, 2012

Auto Resizing Images for Mobile Screens


One thing that I found out very quickly when working with jQuery Mobile was that my images did not auto resize to the device. If I made an image that was fairly large and looked ready for an iPad screen, that same image would be off in some way when viewed from an iPhone.
REMOVE HEIGHT AND WIDTH FROM YOUR IMG TAGS
After doing some research I found a simple fix that I wanted to share. There are a couple of things you need to do but the first thing is to not assign width and height dimensions for your images. For example, when you are inserting an image inside your HTML, typically you assign a width and a height to the image you insert, but when you are working with multiple screen sizes you don’t want your images to always be that size. If you assign a width and height to the image then no matter what that image will be that width and height and will never resize to the size you need. So again, do not assign width and height attributes to any of the images you want to resize, and it should look something like this

ADDING THE CSS TO MAKE IT ALL WORK
Now comes the important part, After you have removed all the width and height attributes from your img tags add this section to your main css file.
img, object{ max-height:90%; max-width:90%; }
You can change the max-height and max-width to whatever you want but we are addressing the objects within the img tags which in this case is the actual images and saying you have a max height/width of 90% that means you cannot go beyond 90% of the screen real-estate so if your image is wider than 90% it will auto resize but it will keep your image proportional. So I can take an image that would look great on an iPad and use it for an iPhone and not worry about it going off the screen.
CENTERING THE IMAGE
One other thing I am asked a lot is how to center the image. If you are targeting mobile then most likely the browser will support HTML5 so you can use HTML5′s center tag to accomplish this like the following.
<center><br /></center>
By wrapping the image inside of the center tags, it will always center my image in the middle of the screen. You can do this with any HTML element so it does not have to be an image.

No comments: