Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I position an image in a box such that it fits exaclty in width or heigth, whichever is smaller?

I want to load some photos from a server and display each of them in an own box such that the box is filled and the image centered (not stretched), if it is to big. Can I achieve this for example with CSS without knowing the size of each image? Maybe with max-width or so?

Here is an example of what I want:

An example.

like image 953
AME Avatar asked Oct 24 '22 02:10

AME


1 Answers

You could use the CSS3 background-size property.

Specifically, you would use either background-size:contain or background-size:cover.

From the spec:

Values have the following meanings:

‘contain’

Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.

‘cover’

Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

Source: http://www.w3.org/TR/css3-background/#the-background-size

Which one you used would depend on the aspect ratio of the original images you are using.

Scroll down on this resource to see some examples: http://www.css3.info/preview/background-size/

like image 187
Jason Gennaro Avatar answered Oct 26 '22 20:10

Jason Gennaro