七种简单又好记的css样式使div盒子水平垂直居中!!!
html样式
<div class="big">
<div class="small"></div>
</div>
第一种:使用margin
.small{
width: 200px;
height: 200px;
background-color: pink;
margin: 0 auto;
}
第二种:使用flex
.big{
display: flex;
justify-content:center;
align-items: center;
background-color:red;
}
.small{
width: 200px;
height: 200px;
background-color: pink;
}
第三种:使用flex加margin
.big {
display: flex;
background-color:red;
}
.small {
width: 200px;
height: 200px;
background-color: pink;
margin:auto;
}
第四种:使用定位+margin 1
.big {
position: relative;
height: 300px;
background-color: red;
}
.small {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
第五种:使用定位+margin 2 ,但是要知道外面盒子的宽高
.big {
position: relative;
height: 300px;
width: 300px;
background-color:red;
}
.small {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
第六种:使用定位+ transform
.big {
position: relative;
height: 300px;
background-color:red;
}
.small {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
第七种:line-height + display: inline-block
.big {
height: 300px;
line-height: 300px;
text-align: center;
}
.small {
display: inline-block;
background: pink;
width: 200px;
height: 200px;
}
结果: