Code Junkie
Code Junkie

Reputation: 7788

fluid image inside fluid container

I'm facing a rather challenging html/css problem. I'm trying to build an image gallery with thumbnails below. The design needs to be fluid and able to scale down for mobile.

The requirements,

  1. Container needs to maintain 4:3 aspect ratio regardless of image size within
  2. Container max-width 665px and the min-width:300px
  3. Image within needs to align center / middle
  4. When the browser scales down the container to the point in which it meets one of the image sizes, the image must scale down with the container.

I've successfully been able to get the container to scale correctly with the code below, but the image doesn't maintain vertical middle nor does it scale with the container. The container scales behind the image as if the image is just floating on top of the container.

JS Fiddle Example

http://jsfiddle.net/2kmtmzxv/18/

Example code

<div id="image-container">
    <div id="dummy"></div>
    <div id="image">
         <div>
             <img src="http://www.gannett-cdn.com/-mm-/d3038439ef7e9ad854298da49122ea72ad452f6a/c=186-0-2724-1908&r=x513&c=680x510/local/-/media/USATODAY/USATODAY/2014/08/22/1408738143000-2015-Chevrolet-CorvetteZ06-026.jpg"/>
         </div>
   </div>
</div> 

css

#image-container {display:inline-block;position:relative;width:100%;max-width:665px;min-width:300px}
#dummy {padding-top:75%/* 4:3 aspect ratio */}
#image {position:absolute;top:0;bottom:0;left:0;right:0;background-color:grey}
#image div img{display:block;margin:auto;vertical-align:middle;width:100%;max-width:400px}

UPDATE

I was able to get the image to scale within by adding width:100% to the image. I still can't get it to vertically align middle though.

Upvotes: 2

Views: 2622

Answers (2)

Lorien
Lorien

Reputation: 36

To center the image, on the img css add

positon:absolute; top:0; bottom:0; left:0; right:0;

This will absolutely position the image relative to its closest non static element (which in this case is #image)

Here is a fiddle: http://jsfiddle.net/dzgvh453/

Upvotes: 2

CMartin14
CMartin14

Reputation: 1

You have this options

Background image instead of actual image Simply have a thumbnail that at-least have a min-height and width. then use the image as background, center, and no-repeat.

Scalable image width: Simply have a thumbnail that at-least have a min-height and width, then put your inside it with 100% width.

Your second option is the easiest way to do it. I simply added width:100% to #image div img http://jsfiddle.net/3e90xxge/#image div img { width: 100%}

Upvotes: 0

Related Questions