这是一个老生常谈的话题,也是面试当中最常见的一个基础问题,总结一下共大家参考:
1,div{
width:100px;
height: 100px;
background:green;
position: absolute;
left:50%;
top:50%;
margin-left:-50px;
margin-top:-50px;
color:#fff;
}
2、.box{
height:1200px;
display:flex;
justify-content:center;
align-items:center;
}
box>div{
background: green;
width: 200px;
height: 200px;
color: #fff;
}
3、div{
width: 200px;
height: 200px;
background: green;
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
效果图和上面类似,可以自己复制代码测试
PS:兼容性:IE7及之前版本不支持
4、div{
width: 200px;
height: 200px;
background: green;
position:absolute;
left:50%; /* 定位父级的50% */
top:50%;
transform: translate(-50%,-50%); /*自己的50% */
}
PS:兼容性:IE8不支持;
5、<div class="outerBox tableCell">
<div class="ok">
<div class="innerBox">tableCell</div>
</div>
</div>
/*table-cell实现居中将父盒子设置为table-cell元素,设置text-align:center,vertical-align:middle;子盒子设置为inline-block元素*/
.tableCell{
display: table;
width:100%;
height:600px;
}
.tableCell .ok{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.tableCell .innerBox{
display: inline-block;
}
6、<div class="outerBox calc">
<div class="innerBox">calc</div>
</div>
/*绝对定位,clac计算位置*/
.calc{
position: relative;
}
.calc .innerBox{
position: absolute;
left:-webkit-calc((500px - 200px)/2);
top:-webkit-calc((120px - 50px)/2);
left:-moz-calc((500px - 200px)/2);
top:-moz-calc((120px - 50px)/2);
left:calc((500px - 200px)/2);
top:calc((120px - 50px)/2);
}
网友评论