5

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.

AME
  • 2,499
  • 5
  • 29
  • 45

3 Answers3

3

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/

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86
0

The quickest thing that you can do is to put the image as a background image that is centered:

style="background: url(images/42.png) 50% 50% no-repeat"

Images smaller than the box will be centered in the box. Images that are larger will experience cropping.

The downside is, there is no scaling.

For scaling, you would have to know the dimensions, employ some math to calculate a scaling amount that will preserve the aspect ratio and use an actual element that is inside a cropping container that uses "overflow: hidden".

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
0

Here what you do. If for instance the image is inside a DIV with an ID called "boxer" You'll now create a CSS that will automatically re-size every image that's inside the DIV with the ID "boxer" The CSS will look like this

#boxer img {
 Width: 600px
 Height: 600px;
}

The above CSS will automatically re-size whatever image you put inside to the specifications in the CSS. This will fit the box with the ID "boxer" precisely if the dimensions corresponds to that of the CSS. You could just do 100% for both the width and the height, that way it fits the box.

Dz.slick
  • 433
  • 1
  • 5
  • 19