I noticed that if I only specify one dimension of an image, either using the width and height attributes on the img tag or using CSS, the browser automatically scales the other dimension proportionally.
For example, if I have a 100×150 image, and I specify width="50" or width:50px;, the browser automatically sets the height to 75 pixels.
Does this does this behavior apply to all browsers? Can I omit one just to save time? I’m preloading images with JavaScript and inserting them dynamically, so I don’t have to worry about the images affecting the layout while downloading.
Yes, this is part of the CSS2 specs:
Defined CSS width or height will scale them properly in any CSS2 compliant browser (I tested it in IE6 and above).
And I consider this a very useful feature. Assume I have a forum with
800pxwidth layout and I allow users to upload images. Setting posts’ images tomax-width:790pxwithout a defined height (height:autoas per default) will automatically make them fit without breaking my layout while keeping the correct aspect ratio. Neat stuff. Note:max-widthisn’t supported in IE6.Obviously, the same applies if you define a CSS
heighthavingwidth:auto.And here’s a Fiddle for testing. Apparently, HTML attributes will also scale properly in virtually all browsers. But I do still recommend doing the element styling with CSS, for the consistency and keeping the markup clean. Styling should be done through CSS.