有时候为了使页面元素看起来更美观,常常会让元素水平居中,垂直居中。下面总结了几个常用的方法。
首先HTML结构如下:
1 <div class="out">2<div class="in">布局</div>3 </div>
方法1、使用最流行的flex布局方案。
1 .out {2display: flex;3justify-content: center;4align-items: center;5 }
方法2、使用定位和偏移
1 .out {2 position: relative;3 }4 .in {5 position: absolute;6 top: 50%;7 left: 50%;8 transform: translate(-50%, -50%);9 }
使用transform可以不用考虑内部元素的宽高。
方法3、使用定位和负margin
1 .out { 2 position: relative; 3 } 4 .in { 5 position: absolute; 6 top: 50%; 7 left: 50%; 8 margin-left: -25px; 9 margin-top: -12.5px;10 }
此时,需要明确内部元素的宽高。(这里设置的内部元素in是高25px,宽50px)
方法4、使用定位和margin:auto;
1 .out { 2 position: relative; 3 } 4 .in { 5 position: absolute; 6 top: 0; 7 left: 0; 8 right: 0; 9 bottom: 0;10 margin: auto;11 }
如果内部只有文本没有标签,如下:
<div class="table">直接文字居中</div>
则可以设置:
.table {width: 200px;height: 100px;display: table-cell;text-align: center;vertical-align: middle;border: #00f solid 1px;}
或者是设置 line-height 为元素高度。
几个简单的是元素水平居中垂直居中的方法,有新方法再继续补充。