Search code examples
csstwitter-bootstrapcss-floatcenteringphoto-gallery

How to center a floated image gallery


I would like the content of the .container to be centered. I am using the float:left property to create the gallery. It is also part of the code to resize and crop the thumbnails.

Any way to do this at all?

CSS:

.grid-item { 
    float: left;
    width: 175px;
    height: 120px;
    overflow: hidden;
}
.grid-item img {
    display: block;
    max-width: 100%;
    border: 2px solid #fff;
    border-radius: 5px;
    margin: 0 auto;
}

HTML:

<div class="container text-center">
    <div id="links">
        <a href="img.jpg" title="" class="grid-item" data-gallery>
            <img src="img.jpg" alt="" class="img-rounded">
        </a>
        <a href="img.jpg" title="" class="grid-item" data-gallery>
            <img src="img.jpg" alt="" class="img-rounded">
        </a>
        <a href="img.jpg" title="" class="grid-item" data-gallery>
            <img src="img.jpg" alt="" class="img-rounded">
        </a>
    </div>
</div>

Solution

  • You should use flexbox to align your contents and you can read the comments in the CSS as to why which property is meant for. Hope, it helps.

    #links{
    display: flex;  /*Generates a flexbox layout with default flex direction as row */
      width: 100%; /* Not really required */
      align-items: center; /*Aligns contents vertically */
      justify-content: space-around; /*Aligns contents horizontally */
      text-align: center; /*Aligns further text in the center */
      flex-direction:row; /*By default its row, you can change to column for vertical alignment */
      flex-flow:row wrap; /*To wrap items in other row when no more can be fit in the same row*/
    }
    
    .grid-item {
      /* flex:1; If you need them to grow or shrink flexibly */
      width: 175px;
      height: 120px;
      overflow: hidden;
    }
    
    .grid-item img {
      display: block;
      max-width: 100%;
      border: 2px solid #fff;
      border-radius: 5px;
      margin: 0 auto;
    }
    <div class="container text-center">
      <div id="links">
        <a href="http://via.placeholder.com/400x400" title="" class="grid-item" data-gallery>
          <img src="http://via.placeholder.com/400x400" alt="" class="img-rounded">
        </a>
        <a href="http://via.placeholder.com/400x400" title="" class="grid-item" data-gallery>
          <img src="http://via.placeholder.com/400x400" alt="" class="img-rounded">
        </a>
        <a href="http://via.placeholder.com/400x400" title="" class="grid-item" data-gallery>
          <img src="http://via.placeholder.com/400x400" alt="" class="img-rounded">
        </a>
      </div>
    </div>