HippoDuck
HippoDuck

Reputation: 2204

Issue with keeping images ratios, and displaying in the middle of a div

I am using bootstrap

I have a row of 4 images. Each image is a different size and aspect ratio. some tall and thin, some short and wide.

I am trying to get them to display within four boxes, centered both vertically and horizontally, without overflowing or being squashed. How can I do this?

Currently I have this: Currently

I would like to get it to display like this: enter image description here

HTML:

<div class="row list-group">
    <div class="item col-xs-3 featured_product">
        <div class="imagecontainer">
            <img src="http://dummyimage.com/200x900/a3a3a3/3b3b3b.jpg" />
        </div>
    </div>
    <div class="item col-xs-3 featured_product">
        <div class="imagecontainer">
            <img src="http://dummyimage.com/700x300/a3a3a3/3b3b3b.jpg" />
        </div>
    </div>
    <div class="item col-xs-3 featured_product">
        <div class="imagecontainer">
            <img src="http://dummyimage.com/600x100/a3a3a3/3b3b3b.jpg" />
        </div>
    </div>
    <div class="item col-xs-3 featured_product">
        <div class="imagecontainer">
            <img src="http://dummyimage.com/200x200/a3a3a3/3b3b3b.jpg" />
        </div>
    </div>
</div>

CSS:

.imagecontainer {
    width:100%;
    height:300px;
    border:1px solid;
    padding:10px;
    text-align: center;
    margin: 1em 0;
}
.imagecontainer img {
    width:100%;
    vertical-align: middle;
    max-height:290px;
}

JSFiddle: http://jsfiddle.net/0kt00prh/

Upvotes: 0

Views: 37

Answers (2)

Andrew
Andrew

Reputation: 1880

Try this for a solution:

.imagecontainer {
    width:100%;
    height:300px;
    border:1px solid;
    padding:10px;
    text-align: center;
    margin: 1em 0;
    position:relative;
    overflow:hidden;
}
.imagecontainer img {
    width:100%;
      position: absolute;
  top: 50%;
left:50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

It will only work for more modern browsers. IE9+

JSFIDDLE

Upvotes: 1

Stickers
Stickers

Reputation: 78716

You could try this, it's using css transform works on IE9 and up. and using transparent borders for the spacing, there might be other ways for doing it but it seems working good.

http://jsfiddle.net/0kt00prh/1/

.imagecontainer {
    position: relative;
}
.imagecontainer img {
    max-height:100%;
    max-width: 100%;
    border: 10px solid transparent;
    position: absolute;
    left: 50%;
    top: 50%;
    transform:translate(-50%, -50%);
}

Upvotes: 3

Related Questions