小div盒子在大div盒子中如何水平垂直居中
关于如何设置小盒子在大盒子里面水平垂直方向同时居中的实现方法有很多种,下面列举了常用的几种。
基础代码样式
html代码
// 大盒子嵌套小盒子 小盒子水平垂直居中
<div class="parent">
<div class="child"></div>
</div>
css代码
.parent{
height:600px;
width:600px;
background-color:red;
}
.child{
height:300px;
width:300px;
background-color:chocolate;
}
1.使用定位实现
父盒子相对定位,子盒子绝对定位,top为父盒子的50%(将整个子盒子看成一个点),当移动父盒子的50%,相当于多移动子盒子宽度的50%,所以需要margin-top向上移动-50%
.parent{
height:600px;
width:600px;
background-color:red;
position: relative;
}
.child{
height:300px;
width:300px;
background-color:chocolate;
position: absolute;
top:50%; // 相当于父盒子高的50%
left:50%; //相当于父盒子宽的50%
margin-top: -150px; /*这里是小盒子高的一半*/
margin-left: -150px; /*这里是小盒子宽的一半*/
//top:25%; 也可以实现
//left:25%;
}
2.使用margin:auto
实现
设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子
的居中;
.parent{
height:600px;
width:600px;
background-color:red;
position: relative;
}
.child{
height:300px;
width:300px;
background-color:chocolate;
position: absolute;
top:0;
left:0;
right: 0;
bottom: 0;
margin: auto;
}
3.使用display:table-cell;
display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签,组合使用vertical-align,text-align,可以使父元素内的所有行内元素水平垂直居中(也就是将内部的元素设置display:inline-block)
.parent{
height:600px;
width:600px;
background-color:red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child{
height:300px;
width:300px;
background-color:chocolate;
display: inline-block;
}
4、弹性盒子实现
只用给父盒子display: flex,不需要给子盒子设置。
.parent{
height:600px;
width:600px;
background-color:red;
display: flex;
justify-content: center;
align-items: center;
}
.child{
height:300px;
width:300px;
background-color:chocolate;
}
实现图片遮住div,显示图片颜色
react被遮盖住,此时通过设置z-index
属性,实现图片遮住div,显示图片颜色
css代码
height: 100px;
width: 100px;
margin: 10px 580px;
position: absolute;
display: inline-block;
background-repeat: no-repeat;
z-index: 3;