tags:

views:

44

answers:

1

I have a 70 by 50 px box and I have various images, (SVG files, so no size) I want to keep their aspect ratio, but some images are portrait and some are landscape sized. So I can do:

background-size: 70px auto;

and that will work for all the landscape icons. But it will stretch the portrait images and make them taller, so they will still have the correct aspect ratio but the top and bottom will be cut off.

is there some kind of background-max-size?

(alternatively, the only reason I'm using background image is because you can center align the image, horizontally and vertically, so the alternative is to find how to vertically align an img element within a li element.)

A: 

This is a problem that CSS can't solve on its own. There are JavaScript libraries that will do this job. If you use jQuery, you can find a plugin or roll your own function.

Grab the width and height of the image, and calculate the ratio (x/y). If the ratio is greater than 70/50 (1.4), set the width to 70px and the height to (70 * x/y). If the ratio is less than 70/50 (1.4), set the height to 50px and the width to (50 * x/y).

Also see CSS vertical-align

If you use browsers that don't support vertical-align, you can position the image absolutely at 50%, and set the top margin to (width * -0.5) using JavaScript. That will align the middle of the image with the middle of the parent element, which is the same as vertical center alignment.

kijin
Ugh, why can't CSS just do center vertical align like it does horizontal centering. CSS could be so much easier, sensible an obvious !!!
Jonathan
@Jonathan CSS can do vertical-align just fine, only Microsoft screwed it up as usual. Don't blame CSS, blame M$ :)
kijin
Microsoft? what they got to do with it? And if I out vertical-align:centre on the imgs parent it dos not align vertically
Jonathan
@Jonathan vertical-align must be "middle", not "center" (Yeah, it's inconsistent.)
kijin
@kijin, right :) I meant middle, I used middle in my code, just wrote center here.
Jonathan
@Jonathan hmm, I thought it was only IE. This is sad...
kijin