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
The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.
First, the <span> tag sets the height of <div> tag using the line-height property. The <span> also becomes an inline-block with the use of the vertical-align: middle. With <span> now an inline-block, it can be set at middle by using vertical-align: middle which works great for inline-block elements.
Deprecated as an attribute Occasionally you will see “valign” used on table cells to accomplish vertical alignment. e.g. <td valign=top> . It should be noted that this attribute is deprecated and should not be used.
Use a p or div rather than a span. Text is an inline element and so is a span. For text-align to work, it must be used on a block level element (p, div, etc.) to center the inline content.
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;
}
Update you CSS to
.container {
width: 100%;
height: 50px;
display: table-cell;
border: 1px solid black;
text-align: center;
vertical-align: middle;
}
.container span {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With