Johhan Johhan - 5 months ago 34
CSS Question

Align elements in a row and horizontally centered in their column

I'm trying to make a grid with some icons and their respective id.

For example, I have this code using bootstrap:



.flex {
display: flex;
align-items: center;
height: 200px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet" />
<div class="row flex">
<div class="col-md-2">
<img src="http://placehold.it/300x300" alt="" class="img-responsive">
<p class="text-center channel-number">2</p>
</div>
<div class="col-md-2">
<img src="http://placehold.it/300x100" alt="" class="img-responsive">
<p class="text-center channel-number">4</p>
</div>
<div class="col-md-2">
<img src="http://placehold.it/300x400" alt="" class="img-responsive">
<p class="text-center channel-number">11</p>
</div>
</div>





now the number will just stay right under the image, but I want the number to be horizontally align with the other numbers and centered below the image.

How can I do this?

Using flex or does bootstrap has a way of doing this?

Thanks!

Fiddle

Answer

Try this:

HTML (no changes)

CSS

.flex {
  display: flex;
  min-height: 200px;
}

.flex > .col-md-2 {
  display: flex;                   /* create nested flex container */
  flex-direction: column;          /* stack children (image and number) vertically */
}

img { margin: auto;}               /* forces numbers to bottom edge of container */

Revised Fiddle

Learn more about justify-content and auto margins here: