2010-12-14 165 views
2

可能重複:
What's The Best Way of Centering a Div Vertically with CSS如何垂直居中div?

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

現在,它似乎並沒有工作。前50%不會垂直居中。這是一點點底部。就好像上邊界是50%。

+0

試首先添加一個任意的高度 – 2010-12-14 01:55:33

回答

1

如果你可以指定框的高度,你可以使用margin-top: -[height/2]px(填寫[height/2]和注意,大多數瀏覽器將全面小數像素放大100%)。

如果你可以指定其父的高度,你可以做這樣的事情:

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

如果孩子的內容,預計會換到多行,你可以在一個子包起來孩子重置line-height

1

top: 50%;不正是你懷疑什麼:它把頂部邊緣在50%的高度。您也可以通過應用等於元素高度一半的負垂直邊距來抵消該效應。例如,如果該元素是100像素高,你想補充一點屬性:

margin-top: -50px; 
1

如果元件的高度是固定的,那麼就以下

的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)** 
} 

其他垂直居中動態高度DIV,你需要的JavaScript ..

document.getElementById('myElement').style.marginTop = (-1) * document.getElementById('myElement').offsetHeight/2