efarley efarley - 2 months ago 9
CSS Question

Flexbox not vertically centering inline-block spans

I have a dashboard I am setting up that has wrapper blocks with a sprite icon that should be centered vertically and horizontally inside its parent.

I got the blocks to be placed how I want and wrapping how I want using flexbox.

I also have the icon centered horizontally using the

text-align
property, but for some reason
justify-content: center
doesn't do anything when I add it to the
.view
or
.sprite-icon
elements; adding it to the
.views
element also doesn't center things how I want and it breaks the padding between the
.view
blocks.

See my JSFiddle I set up showing the issue here: https://jsfiddle.net/efarley/k0m4nxny/



.views {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-around;
}
.view {
height: 105px;
text-align: center;
width: 105px;
}
.sprite-icon {
background-image: url('http://67.media.tumblr.com/b2336d673e315081b6d657f8258c313d/tumblr_mv98xzSiJu1qhori9o1_500.jpg');
display: inline-block;
height: 35px;
width: 35px;
}
.sprite-icon.one {
background-position: 0 0;
}
.sprite-icon.two {
background-position: 0 35px;
}
.sprite-icon.three {
background-position: 0 70px;
}

<div class='views'>
<div class='view'>
<span class='sprite-icon one'></span>
</div>
<div class='view'>
<span class='sprite-icon two'></span>
</div>
<div class='view'>
<span class='sprite-icon three'></span>
</div>
</div>




Answer

You need to make your view a flex container, then add flex centering properties.

.view {
  height: 105px;
  text-align: center;
  width: 105px;
  display: flex;             /* new */
  align-items: center;       /* new */
  justify-content: center;   /* new */
}

revised fiddle

Note that the justify-content property only applies to flex containers. In your question, you were applying it to a flex item. That's why it failed.

Learn more about flex centering: