How to make a responsive grid of photos using Twitter Bootstrap if heights are different

Dave picture Dave · Feb 1, 2014 · Viewed 16.5k times · Source

How can I Twitter Bootstrap 3's 'img-responsive' images, but allow them to have a set height so that a grid of photos will flow (unlike the below image)?

I've tried setting the image height attribute, and max-height attribute, but it seems to ignore those unless I set it's height with '!important', but then they look bad and not really in a grid because they take up so little horizontal space.

I've tried a few tricks related to putting them as background images of divs, and overflow:hidden, but everything I've tried 1) doesn't work, and 2) seems hacky 3) looks messed up. (tried going through this one, as an example)

The images are slightly bigger than the area they fill, as I want them to be able to show bigger on large monitors, so even if I did get the background image thing to work, it would be showing a zoomed-in version of the image, since the background doesn't know to scale-down to fit.

This seems like it HAS to be a common occurrence - is there a somewhat simple way to handle it?

photo gallery

Answer

Josh Harrison picture Josh Harrison · Feb 1, 2014

I'm not familiar with bootstrap, but I'm sure you could wrap each img in a div.wrapper, and apply something like this to the divs:

div.wrapper {
    width: 33%;
    height: 200px; /* or whatever... */
    overflow: hidden;
    float: left;
}

Then to handle image scaling:

.wrapper img {
    max-width: 100%;
    height: auto;
} 

EDIT - ALTERNATIVE METHOD

To achieve what you want I think the best way will be to use background images on an alternative element, with background-size: cover, instead of img tags.

HTML:

<a href="path/to/full_size.jpg" class="image" style="background-image: url(path/to/image.jpg);">Link Text Here</a>

Repeat for each of your images in the grid, instead of using img tags.

CSS:

.image {
    display: block;
    text-indent: -1000px; /* hide link text */
    overflow: hidden;
    background-size: cover;
    width: 33%;
    height: 200px;
    float: left;
}

Note that background size is not supported in IE versions 8 and below, if that matters to you.