Nathan Gilford Nathan Gilford - 6 months ago 20
CSS Question

Center unknown (responsive) number of images that are floated

I am creating a list of employees, with their photos in a grid format (5 wide). As the number of employees fluctuates I need to be able to center floated elements that don't fill a whole row, without using a containing div for each row. I really feel like it's unlikely I'm the first to want to do this and is struggling, but every solution I've found is to create a container, or some suggest the

inline-block
solution, however these images need to be flush, and as they are
% width
on some browsers some space can be visible between them, even with the
margin-right: -4px
solution; this is why I am depending on floats. Thanks!

What I have

http://pasteboard.co/1u9iCIRy.jpg

What I want

http://pasteboard.co/1u9lKgCh.jpg

Answer

If you don't want the space between them, simply give their parent container font-size: 0; text-align: center; while using inline-block for the images.

.imagecontainer {
  font-size: 0;
  text-align: center;
}

.imagecontainer img {
  display: inline-block;
}
<div class="imagecontainer">
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
  <img src="http://placehold.it/200x300" alt="" /> 
</div>

http://codepen.io/anon/pen/LZpGbZ