3

Is there a special way to vertically center text in an element using flexboxes (or other pure CSS)?

Fiddle: http://jsfiddle.net/WK_of_Angmar/JZZWg/

<body>
<div id="main">
    <section id="a">Test1</section>
    <section id="b">Test2</section>
</div>

#a {
    flex: 1 0 auto;
}
#b {
    flex: 0 0 auto;
    min-height: 3em;
    background-color: yellow;
}
#a {
    background-color: blue;
}
#main {
    display: flex;
    flex-direction: column;
    height: inherit;
}

body {height: inherit;}
html {height: 100%;}
Wk_of_Angmar
  • 572
  • 6
  • 14
  • Accidentally asked here instead of Stack Overflow. Would appreciate a move. :-) – Wk_of_Angmar Mar 23 '13 at 21:42
  • With flexbox you can vertically center a flex element inside a flex container, but flexbox doesn't provide support for centering text content within a flex element. You'll need to use the same tricks as for centering text in a non-flex element. – Matt Coughlin Mar 24 '13 at 02:46

1 Answers1

6

Using line-height is one solution, here's the link to Fiddle.

Update: I took a little more interest in the flex model and found the centering properties, so I guess this makes a better solution for you (although not that neat and elegant because of all the prfixes). Here is the link to Fiddle using flex properties for alignment.

And here is a link that explains the usage of the properties.

  • Ahh, can't believe I forgot about this. If nobody provides a more elegant solution, I'll accept. – Wk_of_Angmar Mar 23 '13 at 22:13
  • Fair enough though there is another option to go with (using vertical-align and an image) the line-height is probably more elegant. Here is a link to an article that describes both solutions: http://hu.je/example – Miloš Miljković Mar 23 '13 at 22:21
  • For a single line of text that will never wrap around to a second line, and is inside a container with a fixed height, this is the most elegant solution possible. Does it suit your requirements? (if not, you'll need a different solution) – Matt Coughlin Mar 24 '13 at 02:41
  • I don't expect the content to wrap, but that does not account for what could/should happen on edge cases (where it can wrap). As for now, this is what I'm going for, but it does not completely suit my requirement. However, there are hacky workarounds to make this a satisfactory solution. CSS is an absolute mess for creating layouts. – Wk_of_Angmar Mar 24 '13 at 18:27