CSS:垂直居中

1.使用table-cell+vertical-align

- 锐客网.parent{ width:500px; height: 400px; background-color: greenyellow; display:table-cell; vertical-align: middle; } .child{ width:300px; height:200px; background-color:red; }Demo

原理:通过将父框转化为一个表格单元格显示(类似),再通过设置属性,使表格单元格内容垂直居中以达到垂直居中。 优点:兼容性好,ie8以上均支持 2.使用absolute+transform
- 锐客网.parent{ position:relative; width:200px; height:100px; background-color:green; } .child{ width:50%; height:50%; background-color:red; position:absolute; top:50%; transform:translateY(-50%); }DEMO

原理:类似于水平居中时的absolute+transform原理; 3.使用flex+align-items
- 锐客网.parent{ width:300px; height:200px; background-color: green; display:flex; align-items:center; } .child{ width:50%; height:50%; background-color:red; }Demo

4.使用flex+flex-direction+justify-content
- 锐客网.parent{ width:300px; height:200px; background-color:green; display: flex; flex-direction: column; justify-content: center; } .child{ width:50%; height:50%; background-color:red; }DEMO

5.使用absolute+margin负边距
- 锐客网.parent{ width:300px; height:200px; background-color:green; position:relative; } .child{ width:50%; height:50%; background-color:red; position:absolute; top:50%; margin-top:-50px; }DEMO

【CSS:垂直居中】缺点:需知道子元素宽,高;以及高的一半;
6.使用absolute+margin
- 锐客网.parent{ width:300px; height:200px; background-color:green; position:relative; } .child{ width:50%; height:50%; background-color:red; position:absolute; top:0; bottom:0; margin:auto; }DEMO

7.使用padding
- 锐客网.parent{ width:100%; padding:100px 0; } .child{ width:50%; height:100px; background-color:red; }DEMO

原理:设置父元素padding值上下一样,不能设置高度,这样子元素看起来是在中间;

    推荐阅读