几种常用垂直水平居中的方式
本文总结了一下CSS实现水平垂直居中常用的方式有下面这些
通用html代码
<div class="wrap">
<div class="content">
</div>
</div>
第一种父元素相对布局,子元素绝对布局+外边距
.wrap{
width: 1000px;
height: 800px;
background-color: #7FFFD4;
position: relative;
}
.content{
width: 400px;
height: 500px;
background-color: blue;
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
margin: auto;
}
第二种flex布局
.wrap{
width: 1000px;
height: 800px;
background-color: #7FFFD4;
display: flex;
justify-content: center;
}
.content{
width: 400px;
height: 500px;
background-color: blue;
align-self: center;
}
第三种父元素相对布局,子元素绝对布局+transform
.wrap{
width: 1000px;
height: 800px;
background-color: #7FFFD4;
position: relative;
}
.content{
width: 400px;
height: 500px;
position: absolute;
background-color: blue;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
/*或者
margin-left: -50px;
margin-top: -50px;*/
}
第四种 表格
.wrap{
width: 1000px;
height: 800px;
padding: 200px;
background-color: #7FFFD4;
display: table;
}
.content{
width: 400px;
height: 500px;
background-color: blue;
display: table-cell;
vertical-align: center;
}
如有错误,欢迎指出!!!!