Images, max-width, and Mobile
Many web developers prefer to keep as much control over the applications, especially when it comes down to how the application displays on a mobile device. I'll often see developers prevent zooming in mobile browsers, allowing them to manage display size:
A useful snippet for any mobile developer. Another useful snippet, this one a small CSS helper, ensures that your images don't exceed the fixed width on mobile devices:
/* iphone */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
img { max-width: 100%; }
}
/* ipad */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
img { max-width: 100%; }
}
By setting the max-width property of the image, the image cannot bleed to the right of the page, regardless of its size. You can add that same max-width property to images when it comes time for print too:
@media print {
img { max-width: 100%; }
}
Keep this snippet handy for your current and future mobile web and print endeavors; it's just another CSS directive to show your mobile and print users that you care!
Comments
Be Heard!
Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!
If your site has a fixed width of, say 960px why not just do a media query like this? That way you’re not targeting specific screen dimensions (Many Android devices have dimensions other than the iPhone & iPad’s)
@media only screen and (max-width: 960px) {
img { max-width: 100%; }
}
Hi,
While max-width on images seem quite popular technique for responsive mobile designs I had quite important issue with it when developing for older phones such as BlackBerries and Nokias.
When max-width was applied for an image that was bigger than specified maximum the width of the image was correctly scaled down, but not the height – aspect ratio was not kept. It didn’t happen when width was defined as 100%, so it’s clearly a bug with max-height in these browsers.
But it simply makes this approach useless for wider mobile devices support.
I’ve encountered this problem on mobile and certain desktop designs.
I have always used width: auto, height: auto, max-width: VALUEpx. Seems to do the trick.
Don’t forget to add max-height:auto, I think it was IE7 that did not properly scale the image when that’s not present.
All great points gentlemen! Thanks for sharing!
Honestly, I can’t get any of the solutions with width or height auto to get max-width: 100% with correct aspect ratio working on Blackberry (Bold 9700 with OS version 5).
If any of you guys can provide a jsfiddle or some other example that I could try, I’d be glad to check it.
A great place to start a responsive design is this:
http://www.getskeleton.com/#grid
Just add:
and the images scale to fit whatever block it is in…
img class="scale-with-grid" src="images/dinna-sol.jpg" /