Reputation: 4302
I have text in a <div>
that I want centered vertically. Any easy way to do this (non-absolute positioning method).
Upvotes: 1
Views: 990
Reputation: 4247
this is another method:
http://jsfiddle.net/SebastianPataneMasuelli/V2D3L/1/
the trick is to make the height of the div the same value as line-height.
<div>some text</div>
div {
line-height: 100px;
height: 100px;
}
this gives you a line of vertically centered text.
there is a way: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html.
sorry, that uses absolute positioning.
(but it works)
Upvotes: 7
Reputation: 21
Just add the following css to div
display:table-cell;
vertical-align:middle;
you can also see example http://www.templatespoint.com/blog/2010/10/div-vertical-align-middle/
Upvotes: 0
Reputation: 1745
No, unfortunately there is not good way of doing this using CSS. I would suggest using a javascript framework like JQuery or something like that a go to achieve this. Is it just text your are trying to vertically center?
Also, I know many people are reluctant to use tables however html tables will allow you to vertically center your text, so that may be a quick work around if you are not willing to use javascript to achieve this.
So I guess the its either use some javascript and avoid using html tables or just use tables to do your vertical centering for you.
Just for you reference you use the valign attribute on a td element of a table to vertically align its contents.
You could do something like this:
<div id="center-text">
<div id="center-text-inner">
hello there
</div>
</div>
$(document).ready(function() {
$('#center-text-inner').css({
'position' : 'relative',
'top' : ($('#center-text').height() - $(this).height()) / 2
});
});
Upvotes: 0
Reputation: 42480
Yes it is possible - a very thorough investigation can be found here:
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
Upvotes: 1