这个CSS问题在面试中经常会问到,下面总结一下:
给出如下html:
<div class="container"> <div class="box"></div> </div>
要想让类名为box的div水平垂直居中与外部的div,有以下几种写法:
①方法一:定位和需要定位的元素的margin减去宽高的一半
.container{
width: 300px;
height: 300px;
background:#e9dfc7;
border:1px solid red;
position: relative;
}
.box{
width: 100px;
height: 150px;
position: absolute;
top: 50%;
left: 50%;
-top: -75px;
margin-left: -50px;
}
②方法二:定位和margin:auto
.container{ width: 300px; height: 300px; background:#e9dfc7; border:1px solid red; position: relative; } .box{ width: 100px; height: 100px; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }
③方法三:绝对定位和transfrom
.container{ width: 300px; height: 300px; background:#e9dfc7; border:1px solid red; position: relative; } .box{ width: 100px; height: 100px; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }
④方法四:diplay:table-cell
.container{ width: 300px; height: 300px; background:#e9dfc7; border:1px solid red; display: table-cell; vertical-align: middle; text-align: center; } .box{ width: 100px; height: 150px; /*margin: 0 auto;*/ 这个也行 }
⑤方法五:flexBox居中
.container{ width: 300px; height: 300px; background:#e9dfc7; border:1px solid red; display: flex; justify-content: center; align-items:center; } box{ width: 150px; height: 100px; }