居中
- 水平居中
- 垂直居中
水平居中
- 行内元素:对父元素设置text-align:center;
- 定宽块状元素: 设置左右margin值为auto;
- 不定宽块状元素: 设置子元素为display:inline,然后在父元素上设置text-align:center;
- 通用方案: flex布局,对父元素设置display:flex;justify-content:center;
垂直居中
知道子元素宽高情况(以下所有父元素都设置了相对定位)
- 使用position:absolute,设置left、top、margin-left、margin-top的属性(相对父元素) - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10- #children{ 
 width: 100px;
 height: 100px;
 background-color: red;
 position: absolute;
 top: 50%;
 left: 50%;
 margin-left: -50px;
 margin-top: -50px;
 }
- 使用position:fixed,同样设置left、top、margin-left、margin-top的属性(相对浏览器窗口) - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10- #children{ 
 width: 100px;
 height: 100px;
 background-color: red;
 position: fixed;
 top: 50%;
 left: 50%;
 margin-left: -50px;
 margin-top: -50px;
 }
- 使用position:fixed和margin:auto,设置left、right、top和bottom(相对浏览器窗口)如果不设置宽高会覆盖浏览器窗口 - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11- #children{ 
 width: 100px;
 height: 100px;
 background-color: red;
 position: fixed;
 left:0;
 right: 0;
 top: 0;
 bottom: 0;
 margin:auto;
 }
- 使用position:absolute和margin:auto,设置left、right、top和bottom(相对父元素)如果不设置宽高会覆盖父元素 - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11- #children{ 
 width: 100px;
 height: 100px;
 background-color: red;
 position: absolute;
 left:0;
 right: 0;
 top: 0;
 bottom: 0;
 margin:auto;
 }
不知道子元素宽高情况
| 1 | #children{ | 
设置父元素,使内容居中
- 设置父元素line-height等于它的高,使内容垂直居中(常用于文字居中) - 1 
 2
 3
 4
 5
 6
 7- #parent{ 
 width: 100px;
 height: 100px;
 border:1px solid #000;
 line-height: 100px;
 text-align: center;
 }
- 利用display:table-cell和vertical-align:middle使内容垂直居中(适用与多行文本居中) - 1 
 2
 3
 4
 5
 6
 7
 8
 9- #parent{ 
 width: 100px;
 height: 100px;
 border:1px solid #000;
 text-align:center;
 display:table-cell;
 vertical-align:middle;
 
 }
Flex布局
通用,给父元素设置display:flex和align-items:center,考虑兼容
| 1 | #parent{ |