Jon
Jon

Reputation: 8521

Center A Grid Of Thumbnails Within Responsive Container

I have dynamically generated thumbnails that will be inserted inside a container of fluid width. The thumbnails will have a set width/height of 150px and a margin of 5px. I want the tiles to be horizontally centered within the container, but I want each tile to line up below each other to form a grid.

I have written the following code but I am unable to get the thumbnails to be centered within the container. If I remove the float:left;, the thumbnails will be centered but the thumbnails are no longer lined up below each other to form a grid.

How would I modify the CSS to achieve a grid of thumbnails that are centered within a container of fluid width?

https://jsfiddle.net/bL7kfq5s/

<div class="wrapper">
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
</div>

.wrapper {
  width: 600px; /* responsive width */
  background: yellow;
  text-align: center;
  overflow: hidden;
}

.thumb {
  display: inline;
  float: left;
  margin: 0 5px 5px;
  width: 150px;
}

Upvotes: 0

Views: 316

Answers (2)

assefamaru
assefamaru

Reputation: 2789

You can use a sub-wrapper whose width you can set relative to your main wrapper, and float the thumbs within the sub as below:

<div class="wrapper">
  <div class="subwrapper">
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
  <div class="thumb"><img src="http://www.placehold.it/150x150"></div>
</div>

.subwrapper {
  width: 480px;
  margin: auto;
}

https://jsfiddle.net/45sosd29/

Upvotes: 0

sukesh sudharman
sukesh sudharman

Reputation: 110

please replace .thumb with this code

.thumb {
    display: inline-block;
    float: none;
    margin: 0 5px 5px;
    width: 150px;
}

Upvotes: 1

Related Questions