4

Possible Duplicate:
What's The Best Way of Centering a Div Vertically with CSS

.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
top:50%;
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
}

Right now, it doesn't seem to work. top 50% doesn't center it vertically. It's a little to the bottom. It's as if the top border is 50%.

Community
  • 1
  • 1
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

4 Answers4

2

How to vertically center a div for all browsers?

Community
  • 1
  • 1
Gaurav
  • 12,662
  • 2
  • 36
  • 34
2

If you can specify the height of the box, you can use margin-top: -[height / 2]px (fill in [height / 2] and note that most browsers will round fractional pixels up at 100% zoom).

If you can specify the height of its parent, you can do something like this:

parent {
    height: [height]px;
}
child {
    /* Make the element part of the inline flow, as vertical-align isn't supported on block elements */
    display: -moz-inline-box; /* Old Firefox doesn't support inline-block */
    display: inline-block;
    /* IE < 8 doesn't support inline-block on native block-level elements */
    *display: inline;
    *zoom: 1;

    /* The interesting bit */
    line-height: [height]px;
    vertical-align: middle;
}

If the content of the child is expected to wrap onto multiple lines, you can wrap it in a sub-child that resets the line-height.

eyelidlessness
  • 62,413
  • 11
  • 90
  • 94
1

top: 50%; does exactly what you suspect: it places the top edge at 50% height. You can offset this effect by also applying a negative vertical margin equal to half of the height of the element. For example, if the element was 100px high, you would add this property:

margin-top: -50px;
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

If height of element is fixed, then do following

Css:

.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
**top:50%;**
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
**margin-top: -(half the height)**
}

else to vertically center a div with dynamic height, you would need javascript..

document.getElementById('myElement').style.marginTop = (-1) * document.getElementById('myElement').offsetHeight / 2
Tarun
  • 5,374
  • 4
  • 22
  • 32