#wrap{
position: absolute;
width: 1000px;
height: 400px;
top: 0;left: 0;right: 0;bottom: 0;
margin: auto;
border: 1px solid black;
}
- 通过绝对定位,并设置
top:0;right:0;bottom:0;left:0;margin:auto;
可以使div#wrap在容器内获得垂直居中。
一些其它的居中方法的复习
- 使用绝对定位和外边距
- 绝对定位的
top
,left
等属性的百分比值与外边距的margin-top
,margin-left
等百分比值一样,都是由外部容器width\height来决定的。与元素本身宽高无关。 - 在知道当前元素的宽度的情况下,通过设置
- 绝对定位的
#outer{
width: 200px;
height: 200px;
position: relative;
}
#inner{
width: 400px;
height: 100px;
margin-left: 50%;
left: -200px;
margin-top: 50%;
top: -50px;
}
- 或者
#inner{
margin-left: -200px;
left: 50%;
margin-top: -50px;
top: 50%;
}
- 使用绝对定位和transform
#wrap {
width: 1000px;
height: 400px;
background-color: sandybrown;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- 使用flex布局
- 对父元素设置flex盒子
display: flex;
align-items: center;
justify-content: center;
文字居中
- 使用line-height使文字居中
font-size: 25px;
color: skyblue;
line-height: 400px;
text-align: center;
将line-height
设置为与外部包裹元素高度的值。注意不能使用百分比,因为百分比是与当前元素的font-size
相计算得到的值。
- 使用
display:table
与vertical-align:middle
相配合- 父元素设置为
display:table
,子元素设置为vertical-align:middle
- 父元素设置为
#wrap{
// some other style
display:table;
}
p{
// some other style
display:table-cell;
vertical-align: middle;
}