Ezra Free Ezra Free - 2 months ago 6
CSS Question

Centering divs with display inline-block causes spacing below rows

In the following example I am trying to create a div that contains any number of other divs which are centered and contain four divs per row (with the last row containing however many are left if the total number of images is not divisible by four).

However, it's causing there to be a small (about 3 pixels) spacing below each row of images. Is there any way to make the images so they have no spacing above/below each row?



.container {
width: 100%;
display: table;
text-align: center;
}
.image {
display: inline-block;
width: 25%;
}
.image img {
max-width: 100%;
margin: 0;
padding: 0;
border: 0;
}

<div class="container">
<a href="#" class="image">
<img src="http://placehold.it/400x400" alt="">
</a>
<a href="#" class="image">
<img src="http://placehold.it/400x400" alt="">
</a>
<a href="#" class="image">
<img src="http://placehold.it/400x400" alt="">
</a>
<a href="#" class="image">
<img src="http://placehold.it/400x400" alt="">
</a>
<a href="#" class="image">
<img src="http://placehold.it/400x400" alt="">
</a>
<a href="#" class="image">
<img src="http://placehold.it/400x400" alt="">
</a>
</div>





Just for good measure, here's a screenshot showing the gap I'm refering to:

enter image description here

Answer

You can fix this by adding vertical-align: top; to your images.

CSS

.image img {
  vertical-align: top;
}

.container {
  width: 100%;
  display: table;
  text-align: center;
}
.image {
  display: inline-block;
  width: 25%;
}
.image img {
  max-width: 100%;
  margin: 0;
  padding: 0;
  border: 0;
  vertical-align: top;
}
<div class="container">
  <a href="#" class="image">
    <img src="http://placehold.it/400x400" alt="">
  </a>
  <a href="#" class="image">
    <img src="http://placehold.it/400x400" alt="">
  </a>
  <a href="#" class="image">
    <img src="http://placehold.it/400x400" alt="">
  </a>
  <a href="#" class="image">
    <img src="http://placehold.it/400x400" alt="">
  </a>
  <a href="#" class="image">
    <img src="http://placehold.it/400x400" alt="">
  </a>
  <a href="#" class="image">
    <img src="http://placehold.it/400x400" alt="">
  </a>
</div>

Comments