最近在总结前端知识,也参加了一些面试,面试中遇到一道题要求垂直水平居,现在对这进行一下总结,也好巩固一下知识。
方案一、flex布局
.layout.flex{
display: flex;
width:100%;
align-items: center; /*在交叉轴上如何对齐*/
justify-content: center; /*在主轴上如何对齐*/
height: 300px;
border: 1px solid #000000;
}
<section class="layout flex">
<h1>flex布局水平垂直居中方案</h1>
</section>
方案二、margin:auto
#content{
position: absolute;
margin: auto;
top:0;
bottom: 0;
left: 0;
right: 0;
width: 300px;
height: 100px;
border: 1px solid blue;
/*将section中的文字也水平垂直居中*/
text-align: center;
line-height: 100px;
}
</style>
<section id="content">
水平垂直居中--margin:auto
</section>
这里的section设置任意的高度和宽度都可以实现水平垂直居中的效果。
方案三、transform
#content{
position: absolute;
top:50%;
left: 50%;
height: 100px;
width: 500px;
border: 1px solid blue;
transform: translate(-50%, -50%);
}
<section id="content">
垂直水平居中--translate
</section>
使用transform方式可居中任意宽高的元素,缺点是transform只有IE10+以及其他现代浏览器才支持,存在兼容性问题。
方案四、表格布局
.container{
width: 60%;
height: 300px;
border: 1px #000000;
display: table;
}
.cell{
display: table-cell;
text-align: center;
vertical-align: middle;
border: 1px solid blue;
}
<section class="container">
<div class="cell">水平垂直居中--table</div>
</section>
表格布局方式兼容性较好
原文:https://www.cnblogs.com/jingmi-coding/p/9218863.html