这水平垂直居中,可谓是面试笔试,屡试不爽~所以今儿总结了一下,方便查阅和学习。
1、知道div的宽高,采用position定位实现
<div class="outer1">
<div class="inner1"></div>
</div>
.outer1{
width:1000px;
height:400px;
background-color:#8297b2;
margin:0 auto; /*顺便说一下,设置margin:0 atuo只能实现水平居中,
垂直方向不能实现居中*/
}
.inner1{
width:500px;
height:200px;
background-color:#d58948;
position:absolute;
left:50%;
top:50%;
margin-left:-250px;
margin-top:-100px;
}
2、元素未知宽度,采用position和transform结合使用
<div class="outer2">
<div class="inner2"></div>
</div>
.outer2{
width:1000px;
height:400px;
background-color:#8297b2;
margin:0 auto;
}
.inner2{
width:500px; //这里假设宽度高度并不知道,设置是因为更好看出水平垂直居中结果
height:200px;
background-color:#d58948;
position:absolute;
transform :translate(50%,50%);
}
3、采用flex布局
<div class="outer3">
<div class="inner3"></div>
</div>
.outer3{
width:1000px;
height:400px;
background-color:#8297b2;
margin:0 auto;
display: flex;/*flex布局*/
justify-content: center;/*使子项目水平居中*/
align-items: center;/*使子项目垂直居中*/
}
.inner3{
width:500px;
height:200px;
background-color:#d58948;
}
4、table-cell布局
<div class="outer4">
<div class="inner4"></div>
</div>
.outer4{
width:1000px;
height:400px;
background-color:#8297b2;
margin:0 auto;
display:table;
text-align:center; /*水平居中*/
vertical-align :middle; /*垂直居中*/
}
.inner4{
width:500px;
height:200px;
background-color:#d58948;
display:table-cell;
}
参考文章:https://blog.csdn.net/qq_27576607/article/details/78697812