文字
Css设置垂直居中的方法:
- 使用line-height属性让文字居中
- 使用css3 flex布局让文字垂直居中
- 使用绝对定位和transform让块状元素垂直居中
- 使用flex布局让块状元素垂直居中
1.line-height
```html
css 垂直居中了—文本文字
<a name="OHCW6"></a>
## 2.flex布局
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 300px;
height: 200px;
background: paleturquoise;
/*设置为伸缩容器*/
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
/*垂直居中*/
-webkit-box-align: center;/*旧版本*/
-moz-box-align: center;/*旧版本*/
-ms-flex-align: center;/*混合版本*/
-webkit-align-items: center;/*新版本*/
align-items: center;/*新版本*/
}
</style>
</head>
<body>
<div class="box">css 垂直居中--文本文字(弹性布局)</div>
</body>
</html>
3.设置块元素垂直居中
1)使用绝对定位和transform
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
.child{
background: #93BC49;
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
</style>
</head>
<body>
<div class="box">
<div class="child">css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中</div>
</div>
</body>
</html>
2)使用flex布局
<html>
<head>
<meta charset="UTF-8">
<title>css 垂直居中</title>
<style>
.box{
width: 300px;
height: 300px;
background: #ddd;
display: flex;
flex-direction: column;
justify-content: center;
}
.child{
width: 300px;
height: 100px;
background: #08BC67;
line-height: 100px;
}
</style>
</head>
<body>
<div class="box">
<div class="child">css 垂直居中了--弹性布局</div>
</div>
</body>
图片居中
<div>
<img src="images/1.jpg">
</div>
1.利用position和margin共同实现
div{
width:200px;
height:200px;
border:1pxsolid#ccc;
position:relative;//父元素设置绝对定位
}
img{
position:absolute;//相对定位
width:80px;
height:50px;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;//使其垂直居中
}