CSS 垂直居中的几种方法
absolute定位垂直居中
- 已知元素宽高
.box1{
width: 300px;
height: 300px;
background-color: #55AA00;
position: relative;
}
.box2{
width: 100px;
height:100px;
background-color: azure;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
``
- 元素宽高未知
.box1{
width: 300px;
height: 300px;
background-color: #55AA00;
position: relative;
}
.box2{
width: 100px;
height:100px;
background-color: azure;
position: absolute;
top:0;
left: 0;
right:0;
bottom: 0;
margin:auto;
}
- 简写方式,推荐使用
.box{
width: 100%;
height: 200px;
background-color: cadetblue;
position: relative;
}
.box1{
width: 50px;
height: 50px;
background-color: burlywood;
position: absolute;
/* top:0;
right: 0;
left: 0;
bottom: 0;*/
inset: 0;
margin: auto;
}
- margin-block & margin-inline 居中
.box{
width: 100%;
height: 200px;
background-color: cadetblue;
position: relative;
}
.box1{
width: 50px;
height: 50px;
background-color: burlywood;
margin-block: auto;
margin-inline: auto;
}
- 使用CSS3垂直居中,宽高未知
.box1{
width: 300px;
height: 300px;
background-color: #55AA00;
position: relative;
}
.box2{
width: 100px;
height:100px;
background-color: azure;
position: absolute;
top: 50%;
left: 50%;
transform:translate(-50%,-50%);
}
flex垂直居中
.box1{
width: 300px;
height: 300px;
background-color: #55AA00;
/* 新版flex */
display:flex;
justify-content: center;
align-items: center;
}
.box2{
width: 100px;
height:100px;
background-color: azure;}