文字

Css设置垂直居中的方法:

  • 使用line-height属性让文字居中
  • 使用css3 flex布局让文字垂直居中
  • 使用绝对定位和transform让块状元素垂直居中
  • 使用flex布局让块状元素垂直居中

    1.line-height

    ```html
css 垂直居中了—文本文字

  1. <a name="OHCW6"></a>
  2. ## 2.flex布局
  3. ```html
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7. <meta charset="UTF-8">
  8. <title>css 垂直居中</title>
  9. <style>
  10. .box{
  11. width: 300px;
  12. height: 200px;
  13. background: paleturquoise;
  14. /*设置为伸缩容器*/
  15. display: -webkit-box;
  16. display: -moz-box;
  17. display: -ms-flexbox;
  18. display: -webkit-flex;
  19. display: flex;
  20. /*垂直居中*/
  21. -webkit-box-align: center;/*旧版本*/
  22. -moz-box-align: center;/*旧版本*/
  23. -ms-flex-align: center;/*混合版本*/
  24. -webkit-align-items: center;/*新版本*/
  25. align-items: center;/*新版本*/
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <div class="box">css 垂直居中--文本文字(弹性布局)</div>
  31. </body>
  32. </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;//使其垂直居中

}