1.使用flex
这是最简单的一种方法,但是此种方法只兼容到IE10以上
<div class="parent"> <div class="child"> <div> 我是child </div> </div> </div>
.parent{ display: flex; align-content: center; justify-content: center; background-color: #42b983; width: 400px; height:400px; } .child{ width: 80%; height: 80%; background-color: #2c3e50; }
2.使用line-height
这种方法仅仅限于文本,当line-height设置为100时,整个子div充满父DIV
.parent{ background-color: #42b983; wi100px;
height:100px;dth: } .child{ line-height: 100px; background-color: yellow; }
3.使用绝对定位+负margin
.parent{ background-color: #42b983; width: 100px; height:100px; position: relative; } .child{ position: absolute; left: 50%; top: 50%; width: 80px; height: 80px; margin-left: -40px; margin-top: -40px; background-color: yellow; }
这种方法有个确定就是子元素的宽高值确定,不能适应自适应布局
4.使用绝对定位+margin
.parent{ background-color: #42b983; width: 100px; height:100px; position: relative; } .child{ position: absolute; left: 0; top: 0; bottom: 0; right: 0; text-align: center; margin: auto 0; width: 80%; height: 80%; background-color: yellow; }
5.使用transform实现居中
这种方法和第三种差不多,就是把负margin变成了transform,这种方法的优点是不用确定子元素的高度,缺点是兼容性不好
.parent{ background-color: #42b983; width: 200px; height:200px; position: relative; } .child{ position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%,-50%); -moz-transform: translate(-50%,-50%); transform: translate(-50%,-50%); }
6.利用父,子元素的高和计算padding值
具体方法为 (父-子)/2 就是padding值,这个值就是父元素的padding
7.使用vertical-align:middle
.parent{ background-color: #42b983; width: 200px; height:200px; /*position: relative;*/ vertical-align: middle; display: table-cell; } .child{ margin: auto; width: 100px; height: 100px; background-color: yellow; }