实例-水平垂直居中对齐
内联元素
- flex方法
.box {
width: 300px;
height: 200px;
background: skyblue;
display: flex;
align-items: center;
justify-content: center;
} - text-align+行高方法(不适合于多行内联元素)
.box {
width: 300px;
height: 200px;
background: skyblue;
line-height: 200px;
text-align: center;
} - table-cell方法
.box {
width: 300px;
height: 200px;
background: skyblue;
display:table-cell;
vertical-align: middle;
}
- flex方法
块级元素
flex方法(同上)
table-cell方法(同上)
绝对定位方法+transform方法
.box {
width: 300px;
height: 200px;
background: skyblue;
position: relative;
}
.box div{
width:200px;
height:50px;
background:pink;
position: absolute;
left:50%;
top:50%;
transform: translate(-50%,-50%);
}绝对定位+margin:auto方法
.box {
width: 300px;
height: 200px;
background: skyblue;
position: relative;
}
.box div{
width:200px;
height:50px;
background:pink;
position: absolute;
left:0;
top:0;
right:0;
bottom:0;
margin:auto;
}