Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically centering text inside flexbox item

I want the flex items to take full height, but the content inside them to be vertically centred.

justify-content: centre doesn't work, and align-self: centre on the item itself shrinks its height to its own content, while I want all items to be the same height.

In this example I want the numbers to be vertically centred: http://codepen.io/ilyador/pen/ogYbWO?editors=110

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;  
}

.flex-item {
  flex: 1 1;
  background: tomato;
  padding: 5px;
  margin-top: 10px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
  border: solid 1px red;
}
<ul class="flex-container">
  <li class="flex-item">1fbdms s s sdj dfkg kjfg dkfj gdfjkgdfkj gdfkjg dfkjgdkhdfjk gkjdfkjdfgdfg jkdfgdfjkgk </li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
  <li class="flex-item">6</li>
</ul>
like image 296
ilyo Avatar asked Jan 01 '15 09:01

ilyo


People also ask

How do I center vertically in flexbox?

Centering Vertically By default flex items will fill vertical space of their parent element. To vertically center our div we can add a single CSS property. By using align-items: center we can vertically center all flex items to the parent container along the cross axis of the flex container.

How do I center text vertically in an element?

Answer: Use the CSS line-height property Suppose you have a div element with the height of 50px and you have placed some link inside the div that you want to align vertically center. The simplest way to do it is — just apply the line-height property with value equal to the height of div which is 50px .


1 Answers

I was able to accomplish vertical centering of your numbers with this:

.flex-item {
  display:flex;
  flex-direction:column;
  justify-content:space-around;
}

If you want something to be vertically centered, set the container to display:flex and then use justify-content to accomplish it. With justify-content you could either set it to space-around or to center. Either will accomplish your goal.

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

like image 128
paceaux Avatar answered Oct 10 '22 01:10

paceaux