盒子垂直水平居中方案(齐)
定位方式居中(三种)
html结构
<body>
<div class="box">盒子垂直居中</div>
</body>
- 知道子盒子的宽度和高度情况下并且要计算考虑
body,html{
position: relative;
height: 100%;
}
.box{
width: 150px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -75px;
margin-top: -50px;
}
- 知道子盒子的宽度和高度情况下不需要计算考虑
body,html{
position: relative;
height: 100%;
}
.box{
position: absolute;
width: 150px;
height: 100px;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
- 不用知道盒子宽度高度(兼容性不太好)
body,html{
position: relative;
height: 100%;
.box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
不基于定位方式居中(一种)
html结构
<body>
<div class="box">盒子垂直居中</div>
</body>
- flex布局(多用于移动端)
body{
display: flex;
justify-content: center;
align-items: center;
}
![]()