1

I have text in a <div> that I want centered vertically. Any easy way to do this (non-absolute positioning method).

chromedude
  • 4,246
  • 16
  • 65
  • 96

4 Answers4

7

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)

1

Yes it is possible - a very thorough investigation can be found here:

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Mike Chamberlain
  • 39,692
  • 27
  • 110
  • 158
0

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
  });

});
Simon H
  • 1,735
  • 12
  • 14
  • ah... didnt think of javascript, I actually am using javascript heavily and the jquery framework so what exactly in it are you talking about? – chromedude Nov 19 '10 at 04:40
0

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/

Eswar
  • 21
  • 1