块元素垂直水平居中的方法
1、使用flex
.parent {
height: 600px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child {
border: 1px solid green;
width: 300px;
}
2、使用transform
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
3、使用margin-top -一半的高度
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
width: 300px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -50px;
}
4、使用绝对布局absolute
和margin:auto
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
width: 300px;
height: 200px;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}