1. 设置父元素height和line-height属性值相等
* 缺点:仅适用于宽度固定的单行文本
2. 设置元素绝对定位(position:absolute),并设置top:50%;margin-height为负的height的一半
* 缺点:元素高度固定
```
.container{
width: 200px;
height: 200px;
border: 1px solid red;
position: relative;
}
.content{
background-color: #ccc;
height: 50px;
width: 100%;
position: absolute;
top: 50%;
margin-top: -25px;
}
<div class="container">
<div class="content"></div>
</div>
```
3. 设置元素绝对定位(position:absolute),并设置top:50%;transform:translateY(-50%);
* 缺点:transform属性浏览器兼容性不好
4. 设置元素vertical-align:middle;并添加父元素:after伪元素,设置vertical-align:middle
* 缺点:仅适用于行内元素、行内块元素
```
.wrapper {
width: 500px;
height: 500px;
background-color: #ccc;
text-align: center;
}
.wrapper:after {
content: '';
height: 100%;
width: 0;
display: inline-block;
vertical-align: middle;
}
.align {
background-color: #f00;
width: 20%;
height: 20%;
display: inline-block;
vertical-align: middle;
}
<div class="wrapper">
<div class="align"></div>
</div>
```
5. 设置父元素display:flex;justify-content:center;
* 缺点:flex布局浏览器兼容性不好
6. 设置元素绝对定位(position:absolute),并设置top:0;bottom:0;margin:auto;
```
.wrapper {
position: relative;
width: 500px;
height: 500px;
border: 1px solid red;
}
.content{
position: absolute;
width: 200px;
height: 200px;
border: 1px solid green;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
}
<div class="wrapper">
<div class="content"></div>
</div>
```