15

http://jsfiddle.net/UmHNL/2/

<div class="container">

    <span>Some text, yay</span>

</div>

<div class="container">

    <span>Some text, yay. But shit time, there is alot of text, so we get a problem with breaking lines and the given height :( How can I align vertical now?</span>

</div>
<style>
.container {
    width: 100%;
    height: 50px;
    line-height: 50px;
    border: 1px solid black;
}

.container span {
    padding-left: 30px;
}
</style>

This solution works great until the screen-width is too small - breaking my text into several lines.

When I google the problem I find so many crazy over-complicated solutions with javascript and divs to push my content in place.. Can anyone help me make this work without adding more markup? :)

There's no need to support Internet Explorer and older browsers.

Thanks

2 Answers2

12

You should try this:

.container {
    width: 100%;
    height: 50px;
    border: 1px solid black;
    display: table;
    text-align: center;
}

.container span {
    display: table-cell;
    vertical-align: middle;
}
osmanz
  • 481
  • 5
  • 15
3

Update you CSS to

.container {
  width: 100%;
  height: 50px;
  display: table-cell;
  border: 1px solid black;
  text-align: center;
  vertical-align: middle;
}

.container span {
}
Ishank Gupta
  • 1,575
  • 1
  • 14
  • 19
  • but why you need `padding-left: 30px;` in the span, you have already centered the text in the .container and make sure you add `vertical-align: middle;` in the .container to vertically align the text. – Ishank Gupta Feb 05 '14 at 12:55
  • 1
    That didn't work, but saying that container is table, and the span table-cell worked better :) –  Feb 05 '14 at 12:55
  • Sorry I linked the wrong fiddle and instead of editing the comment I hit delete :) –  Feb 05 '14 at 12:55
  • Solution: http://jsfiddle.net/UmHNL/7/ –  Feb 05 '14 at 12:56
  • 1
    @Johannes I don't think this is the solution because the second cell doesn't respect the height of 50px – Mihai Matei Feb 05 '14 at 12:58
  • @Johannes: I dont think we should change the display of span to `table-cell`, because it will break when you will add any other tag inside the .container and now I think we do not require any vertical-align as you are adding white space with padding. – Ishank Gupta Feb 05 '14 at 13:04