垂直居中的几种办法

1. 文字垂直居中

单行文字:只要 line-height = height。比如

div{
    height: 30px;
    line-height:30px;    
}

多行文字垂直居中:

将line-height设置为height的n份之一。这个n = 文字行数。再根据需要,配合padding使用。

下面来举一个最简单的例子。比如有一个div容器,设计稿高度为120px,包含3行文字。

div{
     background-color: red;
     width: 200px;
     height: 90px;
     line-height: 30px;
     padding: 15px 10px;
}

效果如下:

2. 大容器包裹下的小容器完全居中(水平和垂直居中)

.div1 {
    background-color: red;
    width: 28em;
    height: 15em;//必须声明元素高度
    margin: auto;
    position: relative;
}
.div2 {
    background-color: white;
    width: 50%; //可以自由调节大小,自适应布局
    height: 50%; //必须声明元素高度
    overflow: auto; //避免元素溢出,显示不正常
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

3. 大容器下有图片和文字需要垂直居中。

实际上,这个也可以参照办法2,用div2将图片和文字包裹起来。div2的高度等于图片的高度。

    html{
        font-size: 16px;
    }
.div1{
    width: 37.5em;height: 18em;
    margin: auto;
    position: relative;
    background-color: red;
}
.div2{
    width: 20em; 
    height: 12.5em; 
    overflow: auto; 
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background-color: white;
}
img{
    vertical-align: middle;
    width: 12.5em;height: 12.5em;
    max-width: 100%;
}

 p{
   display: inline-block;font-size: 2em;
  }

效果如下:

 多张图片和文字,也是一样的办法,根据项目实际情况来调整宽高即可。

关于img之间的缝隙问题,可以戳这里查看解决办法

4. 利用display: flex; align-items: center;这个办法来实现图片和和多行文字的弹性垂直居中。

align-items 属性定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。

align-content 属性在弹性容器内的各项没有占用交叉轴上所有可用的空间时对齐容器内的各项(垂直)。(用于多行,对单行无效)

justify-content:center 水平居中 

设置在容器上的6个属性:

  • flex-direction
  • flex-wrap
  • flex-flow
  • justify-content
  • align-items
  • align-content

html如下:

    <div>
        <img src="images/icons.png" alt="">
        <p>我是文字 <br> 另一行文字 <br>第三行文字</p>
    </div>

CSS:

        div{
            width: 500px;
            height: 250px;
            background: #aedbf0;
            display: flex;
            align-items: center;
        }
        img{
            width: 322px;
            height: 113px;   /* 始终为img设定宽高 */
        }

效果如下:

 

posted @ 2017-04-11 09:00  kiera  阅读(879)  评论(0编辑  收藏  举报