如何垂直居中div?
问题描述:
可能重复:
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%。
答
如果你可以指定框的高度,你可以使用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
。
答
top: 50%;
不正是你怀疑什么:它把顶部边缘在50%的高度。您也可以通过应用等于元素高度一半的负垂直边距来抵消该效应。例如,如果该元素是100像素高,你想补充一点属性:
margin-top: -50px;
答
如果元件的高度是固定的,那么就以下
的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
试首先添加一个任意的高度 – 2010-12-14 01:55:33