How do I center text vertically with css
This question already has an answer here:
You could set your container to display:table-cell
and add vertical-align:middle
:
http://jsfiddle.net/ptriek/h5j7B/1
(But IE7 and below won't like this...)
Well, there are several solutions.
The easiest is
#centerme
{
// will center the text vertically, but looks bad with multiliners
line-height:20em;
}
For multi-liners, you need to position a-box-in-a-box
#parentbox
{
// we need the "parent" to have some kind of height
height:20em;
// the most important... position children "relative" to the parent
position:relative;
}
.childbox
{
position:absolute;
left:0;
top:50%;
margin-top:-5em; // this pulls the child back "up" to the vertical center
}
The problem here is that the "height" of your multi-liner must be known (or at least guessed) so it actually centers vertical.
WHAT YOU NEED TO KNOW
There is no pure CSS way to know about the height of an element, which would then allow us to center it vertically in an "adaptive" way!
This means that when you change the text, you must change the CSS too to make sure it all still fits.
This can be annoying and that's where and why most people fall back on using javascript to work around this CSS annoyance of "a missing feature". In the end, javascript makes it easier on us all (at least in these kind of cases).
MORE
There's a lot of Q&A about this going on around the web and around this website. In case you missed them, here are some:
and there are many more; all providing individual solutions to individual cases. Those will help you get a bit more confident (as you initially stated you're new to this kind of CSS fiddling).
<div style="height:50px;line-height:50px;">
Text
</div>
链接地址: http://www.djcxy.com/p/7168.html
上一篇: 垂直和水平在页面上居中放置<div>的最佳方法是什么?
下一篇: 如何以CSS垂直居中文本