元素垂直居中的几种方法:

方法一:设置height和line-height

在CSS中,line-height 属性设置两段段文本之间的距离,也就是行高,如果我们把一段文本的line-height设置为父容器的高度就可以实现文本垂直居中了,比如下面的例子:

<!DOCTYPE html>
    <html lang=\"en\">
    <head>
       <  charset=\"UTF-8\">
       < >Document</ >
       <style>
       div {
           width: 300px;
           height: 200px;
           border: 1px solid red;
       }
       span {
           line-height: 200px;
       }
      </style>
</head>
<body>
   <div>
       <span>文本垂直居中原理</span>
   </div>
</body>
</html>

 

方法二:display:table-cell和vertical-align

组合使用display:table-cell和vertical-align、text-align,使父元素内的所有行内元素水平垂直居中(内部div设置display:inline-block即可)。这在子元素不确定宽高和数量时,特别实用!

<!DOCTYPE html>
<html lang=\"en\">
<head>
    <  charset=\"UTF-8\">
    <  http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">
    < >Demo001_displayTable</ >
    <style>
        /*** table-cell middle center组合使用 ***/
        .cell {
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            width: 240px;
            height: 180px;
            border:1px solid #666;
        }
    </style>
</head>
<body>
    <div class=\"cell\">
        <p>我爱你</p>
    </div>
    <div class=\"cell\">
        <p>我爱你</p><p>亲爱的中国</p>
    </div>
    <div class=\"cell\">
        <p>我爱你</p><p>亲爱的中国</p><div style=\"width:100px;height:50px;border:1px solid #ccc;display:inline-block\">div(inline-block)</div>
    </div>
</body>
</html>

 

方法三:display:flex;

以前div内部的文字垂直居中,使用height = line-height,现在可以使用display:flex来实现了

.div{
  display:flex;
  align-items:center;
}

使用div类,不仅可以实现div内部的文字居中,还可以使内部的div也垂直居中.

<head>
    <style>
        body{margin: 0; padding: 0 ;}
        .header,.footer{height: 100px;background-color:#ccc;}
        .cc{
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            background-color: #ccc;
            min-height: calc(100vh - 200px);
    }
    </style>
</head>
<body>
<div class=\"header\">by lpy</div>
<div class=\"content\">
    <div class=\"cc\">
            <div>content</div>
    </div>
</div>
<div class=\"footer\">by lpy</div>
</body>

 

方法四:display:-webkit-box

这种方法,在 content 元素外插入一个 div。设置此 div height:50%; margin-bottom:-contentheight;

content 清除浮动,并显示在中间。

<head>
    <style>
.floater {
    float:left; 
    height:50%; 
    margin-bottom:-120px;
}
.content {
    clear:both; 
    height:240px; 
    position:relative;
}
    </style>
</head>
<body>
<div class=\"floater\"></div>  
<div class=\"content\"> Content here </div>
</body>

 

方法五:相对定位和绝对定位

利用给父元素设置相对定位,子元素设置绝对定位、margin: auto 0;和top: 0; bottom: 0;实现垂直居中;

原理:因为auto关键词默认自动分配剩余空间,宽度相对window是固定的,所以margin: 0 auto;可以有水平居中的效果,而高度相对window并不是固定的,所以margin: auto 0;不能垂直居中,所以让子元素的上下margin值不相对于window进行计算,改为相对父元素进行计算即可让margin: auto 0;生效;

#outer{
    position: relative;
}

#inner{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%)
}
收藏 打印