The code below vertically aligns the text within a div perfectly fine but when I try to center it, only the text that needs to be wrapped gets centered. When the text is short, say, 5-6 words, the text is not centered. I don't know if it is just me or I'm doing something wrong here.
I am using display: table-cell;
to do the vertical alignment. Both div
and p
elements are defined in the CSS the same way. Have a look at the codepen to see the problem.
<style>
.outer { outline: 1px solid #eee; }
.outer > p {
display: table-cell;
height: 200px;
vertical-align: middle;
text-align: center;
}
</style>
<div class="outer">
<p>
This longer text will be vertically aligned.
</p>
</div>
<div class="outer">
<p>
This longer text will be vertically aligned and centered. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
</div>
You just need to declare the wrapping outer
class as display: table
and width: 100%
... The children p
's have already been set as display: table-cell
by yourself. Updated codepen: http://codepen.io/anon/pen/VaoOJp
.outer {
outline: 1px solid #eee;
display: table;
width: 100%;
}
.outer > p {
display: table-cell;
height: 200px;
vertical-align: middle;
text-align: center;
}
<div class="outer">
<p>
This longer text will be vertically aligned.
</p>
</div>
<div class="outer">
<p>
This longer text will be vertically aligned and centered. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
</div>