不固定宽高元素水平垂直居中
背景:
本文主要讲述不用flex布局和grid布局时如何设置不定高宽元素的水平垂直居中,这是很多时候经常遇到的问题。
页面结构
<div class="box">
<div class="content"><span>hell</span><br/>ssssssss<br/>shshsh
</div>
</div>
第一种方法(absolute+translate)不兼容ie8,因为这个transform属性不兼容ie8
translate里面的百分比是以自身大小为基准的
.box{
width:400px;
height: 400px;
background-color: skyblue;
position: relative;
}
.content{
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
第二种方法(table-cell+inline-block)不兼容ie67,因为inline-block识别不了
将div设置成表格的单元格,使用vertical-align、text-align属性将内联元素对齐
.box{
width:400px;
height: 400px;
background-color: skyblue;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.content{
display: inline-block;
}
假的方法(top.left.right.bottom为0+margin:auto)
这种方法不知道怎么以讹传讹说能够实现不定宽高的垂直居中的,实际上是不行的,当content没有宽高时会继承父元素的宽高。
//不设置宽高
.box{
width:400px;
height: 400px;
background-color: skyblue;
position: relative;
}
.content{
position: absolute;
top:0;
left:0;
right:0;
bottom: 0;
margin: auto;
}
//设置宽高
.box{
width:400px;
height: 400px;
background-color: skyblue;
position: relative;
}
.content{
position: absolute;
top:0;
left:0;
right:0;
bottom: 0;
width:50%;
height:50%;
margin: auto;
}