1

I'm using bootstrap inside of React to display a grid of images in fixed size boxes. The images are all of different sizes and I don't want to distort them. The behavior I'm looking for is an image displayed in the center of a fixed size box, say 325X250 with a white(or any color) background. I'm really not a CSS person, thus the question.

This is my React code.

return (
      <div className="row">
        <div className="image-viewer">
          {this.state.overlay}
          <ul className="list-inline">
            {this.state.images.map(function (image) {
              return (<li key={image.src}><a href="#" onClick={this.handleClick} data-id={image.mediaId}><div className="img-container "><img
                src={image.src}
                className="img-responsive"
                alt={image.mediaId}/></div></a></li>);
            }, this)}

          </ul>
        </div>
      </div>
    );

This is the styling I've done till now,

.image-container{
  width: 250px;
  height: 300px;
  /*width: 400px;*/
  overflow: hidden;
}
.image-container img{
  height: auto;
  width: 100%;
}

This clearly doesn't work. I've looked into this link,

How can I make all images of different height and width the same via CSS?

But couldn't get any solution to work to my requirement. Any help appreciated.

Community
  • 1
  • 1

2 Answers2

2

As an alternative to the <img> tag, you could use any block level element and CSS background properties:

background-image: url(http://domain.top/path/to/img.png);
background-repeat: no-repeat;
background-size: contain;
background-position: center;

The property background-size and the value contain will render a background image to stretch to it's containing element's edges as far as it can without distortion and will maintain original aspect ratio.

SNIPPET

.img {
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  outline: 1px dashed red;
  width: 325px;
  height: 250px;
  margin: 10px auto;
}
#bbc {
  background-image: url(http://i.imgur.com/4TLlrL3.png);
}
#lena {
  background-image: url(http://i.imgur.com/o1RbMvI.png);
}
#normal {
  background-image: url(http://i.imgur.com/43uy0hP.png);
}
<div id='bbc' class='img'></div>
<figure id='lena' class='img'></figure>
<section id='normal' class='img'></section>
Community
  • 1
  • 1
zer00ne
  • 41,936
  • 6
  • 41
  • 68
0

Try adding 100% to both of them:

.image-container img{
    height: 100%;
    width: 100%;
}

Adding 100% to both of them will have it go full width of parent element