css垂直水平居住实现方法

css实现垂直水平都居中的方法汇总,都是自己亲手实践过的

方法一(height、line-height、text-align)

使用height、line-height 设置相同值,配和text-align设置居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
.box{
height: 100px;
line-height: 100px;
text-align: center;
}
```
**缺点:固定高度,无法实现两行文本的居中**

### 方法二(positionmargin:负值)
父元素设置`position: relative`,使用`position: absolute`,配合margin负值食用。
```css
.box{
width: 100px;
height: 100px;
position:absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
/*简化*/
.box{
width: 100px;
height: 100px;
position:absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}

缺点:需配合父元素食用,固定高度,高度无法自适应内容。元素脱离文档流

方法三(position、margin:auto)

父元素设置position: relative,使用position: absolute,配合margin: auto食用。

1
2
3
4
5
6
7
8
.box{
position:absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}

缺点:需配合父元素食用,元素脱离文档流

方法四(position、transform: translate)

父元素设置position: relative,使用position: absolute,配合transform: translate()食用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
.box{
position:absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
```
**缺点:需配合父元素食用,元素脱离文档流**

### 方法五(display: table-cell
将父元素display改成table表格的形式,再配合`vertical-align: middle`食用。
(即,以表格单元格实现居中)
```html
<style>
.box{
display: table;
vertical-align: middle;
}
.iBox{
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>

<body>
<div class="box">
<div class="iBox"></div>
</div>
</body>

缺点:改变了父元素的display属性。IE6-7不支持display:table-cell

方法六(flex)推荐!!!

flex布局(伸缩布局盒模型,也叫弹性布局盒模型)

1
2
3
4
5
6
7
.box{
display: flex;
align-items: center;
justify-content: center;
/*兼容 IE11*/
display: -ms-flex;
}

缺点:兼容问题,不支持IE11以下(不包括11)