## 前言
css居中是常见的需求,不同场景需要不同的居中方法,本文讨论多种常见居中方法,如有遗漏欢迎补充。
水平居中
- 内联元素
给内联元素的父级加text-align:cente;
1 2 3
| .container{ text-align:center; }
|
1 2 3
| .container{ margin:0 auto; }
|
垂直居中
1. 内联元素设置行高和父级高度一样
1 2 3 4 5 6 7 8
| .container{ height:200px; text-align:center; }
.center{ line-height:200px; }
|
2. 不知道 .parent 的 height
将上下padding的值相等
1 2 3 4 5 6 7 8 9
| .container{ border:1px solid #000; text-align:center; }
.center{ display:inline-blcok; padding:20px 0; }
|
3. table自带功能
1 2 3 4 5 6 7
| <table class="parent"> <tr> <td class="child"> 这里内容会自动居中 </td> </tr> </table>
|
4. div 装成 table
设置display的值为table-cell,将元素变为表格cell显示
1 2 3 4 5 6 7
| .container{ width:600px; height:800px; display:table-cell; vertical-align:middle; text-align:center; }
|
5. 绝对定位
父元素 postion 为 relative 子元素 position 为absolute ,用 transform 属性居中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| .container{ position:relative; width:800px; height:800px; border:1px solid #000; }
.center{ position:absolute; border:1px solid #000; width:100px; height:100px; top:50%; left:50%; transform:translate(-50%,-50%) }
|
6. flex布局
目前的主流方式,非常好用,建议用这种
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| .container{ width:800px; height:800px; border:1px solid #000; display:flex; align-items: center; justify-content: center; }
.center{ width:100px; height:100px; border:1px solid #000; }
|
7. grid布局
Grid布局是一种二维布局方法,能够在行和列中布置内容。因此在任何网格中都有两个轴,横轴(即行轴,内联)和纵轴(即列轴,块)。
沿着这些轴,可以使用盒模型对齐规范中定义的属性对项目进行行对齐和列对齐。
较新的方法,所以有兼容问题,未来会越来越常使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| .container{ width:800px; height:800px; border:1px solid #000; display: grid; align-items: center; justify-content: center; }
.center{ width:100px; height:100px; border:1px solid #000; }
|