- 上面的答案并不完全正确,因为文本仍然不会完全垂直居中。
.wrapper{
margin:5px;
max-height:250px;
min-height:250px;/*not required only height:250px will do*/
border:1px solid green;
}
.content
{
margin:5px;
border:1px solid black;
height:100px;/*you have to give the parent element a height and a width within which you wish to center*/
width:100px;
position:relative;/*giving it a position relative so that anything inside it will be positioned absolutely relative to this container*/
text-align:center;/*aligning the h1 to the center*/
}
.content h1{
border:1px solid black;
position:absolute;
top:50%;
left:50%;
line-height:50px;
width:50px;
margin-left:-25px;/*half the width of the h1 so that it exactly centers*/
margin-top:-25px;/*half the height of the h1 so that it exactly centers*/
}
解释:
-ever 元素html
采用矩形框的形式,因此应用margin-top:50%
将该框的顶部与父元素的 50% 对齐,而不是框内的文本。- 这就是文本与中心不完全对齐的原因。
- 还必须为父元素(您希望在其中居中 h1)提供宽度和高度。
做你正在寻找的正确方法是使用绝对和相对定位。
- 给出相对的.container
位置值和h1
绝对的值
- 通过给 h1 一个宽度和高度,然后我们应用一个等于宽度一半的负左边距和一个等于一半高度的负上边距,以便文本完全居中。