页面中有一个灰色的块:宽高各400px,块中还有一个小的div颜色为粉色:宽高各为200px,如何让这个粉色的块在灰色的块中水平垂直居中呢?
<div class="wrap"> <div class="box"></div> </div>
*{ padding:0; margin:0; } .wrap{ 400px; height:400px; background: grey; } .wrap .box{ 200px; height:200px; background: hotpink; }
1.父相子绝,子: top:0; left:0; right:0 ;bottom:0; margin: auto;
*{
padding:0;
margin:0;
}
.wrap{
400px;
height:400px;
background: grey;
position: relative;
}
.wrap .box{
200px;
height:200px;
background: hotpink;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
margin: auto;
}
2.父相子绝,子:top:50%, left:50%, margin-left:-100px; margin-top: -100px;(这个100px就是子元素的宽高的一半)
.wrap{
400px;
height:400px;
background: grey;
position: relative;
}
.wrap .box{
200px;
height:200px;
background: hotpink;
position: absolute;
top:50%;
left:50%;
margin-left: -100px;
margin-top: -100px;
}
3.父相子绝,子: top:50%; left:50%; transform:translate(-50%,-50%)
.wrap{ 400px; height:400px; background: grey; position: relative; } .wrap .box{ 200px; height:200px; background: hotpink; position: absolute; top:50%; left:50%; transform:translate(-50%,-50%) }
4.flex新版本:父级: display: flex; justify-content: center; align-items: center;
.wrap{ 400px; height:400px; background: grey; display: flex; justify-content: center; align-items: center; } .wrap .box{ 200px; height:200px; background: hotpink; }
5.flex旧版本:display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center;
.wrap{ 400px; height:400px; background: grey; display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center; } .wrap .box{ 200px; height:200px; background: hotpink; }
以上方法亲测有效,