居中
- 情况1:不开启定位,并确定元素大小——margin
- 例子:水平居中
.box1{
width:100px;
height:100px;
background-color: khaki;
margin:150px auto;
}
- 情况2:开启定位,并确定元素大小 ——absolute+margin
- 例:水平垂直居中
.box1{
background-color: orange;
width:50px;
height:50px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
- 情况3: 开启定位,不确定元素大小——absolute+left+top+transform
- 例:水平垂直居中:
.box1{
background-color: khaki;
position: absolute;
left:50%;
top:50%;
transform: translateX(-50%) translateY(-50%);
}
- 情况4:父元素开启弹性盒——justify-content+align-items
- 例:水平垂直居中:
.box1{
width:200px;
height:200px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
}