Reputation: 4054
I have the following scenario in front of me: http://fiddle.jshell.net/fr3TD/
Here i have been trying to vertically align the <p>
tag inside my <div>
. I considered a number of solutions including vertical-align
, mathematically calculating the padding
for my <p>
etc. None of these seem to be the ideal solution since my HTML will be auto-generated and the text inside the span would be variable.
I also spent quite some time searching for the solution on this portal but there seemed to be a consensus that without knowing the height
of the content it is difficult to vertically align it. In my case the height of the content is not known but it is assurred that it will not be greater than the containing <div>
.
Can anyone suggest me a way to find a solution to my problem?
Thanks in advance!!
Upvotes: 2
Views: 184
Reputation: 15709
Try:
p{
display:table;
margin:0;
height:100%;
width:100%;
}
span{
text-align:center;
display:table-cell;
vertical-align:middle;
}
Upvotes: 0
Reputation: 10713
single line
For single lines making the line-height of your p equal to the height of your div is the easiest way.
<div style="background-color:#4F81BD; height: 88px; width: 148px; ">
<p style="text-align:center; line-height: 88px">
<span style="font-size:41px; color:#FFFFFF; ">One</span>
</p>
</div>
http://fiddle.jshell.net/fr3TD/2/
multiple lines
If you want it to work with more than one line you should make your div act as a table cell. Table cells allow vertical centering. This centering is called middle centering. In order to do so add:
display: table-cell; vertical-align: middle
To your div.
<div style="background-color:#4F81BD; height: 200px; width: 148px; display: table-cell; vertical-align: middle">
<p style="text-align:center;">
<span style="font-size:41px; color:#FFFFFF; ">One Two Three</span>
</p>
</div>
http://fiddle.jshell.net/fr3TD/8/
More information about centering: http://css-tricks.com/centering-in-the-unknown/
Upvotes: 3
Reputation: 2343
you should use:
div{
position:relative
vertical-align:middle;
}
p{
position:absolute;
}
here a example: http://fiddle.jshell.net/fr3TD/6/
Upvotes: 1
Reputation: 35983
try with line-height
:
<div style="background-color:#4F81BD; height: 88px; width: 148px; ">
<p style="text-align:center; line-height:88px;">
<span style="font-size:41px; color:#FFFFFF; ">One</span>
</p>
</div>
Upvotes: 1