html中居中显示的几种方式

1. text-align: center; 水平居中
2. 设置line-height;垂直居中
3. display:table-cell;
   vertical-align:middle;
4.  display: flex;
     align-items: center;
     justify-content: center;
5.  背景图片居中 background: url('2.png') no-repeat 50% 50%/32px 32px;

源代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Center</title>
    <style>
        div {
            font-size: 12px;
            width: 100px;
            height: 100px;
            border: 1px solid red;
            margin-bottom: 5px;
        }

        img {width: 32px}

        .div1 {
            text-align: center;
        }

        .div2 {
            line-height: 100px;
        }

        .div3 {
            display:table-cell;
            vertical-align:middle;
        }

        .div4 {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .div5 {
           background: url('2.png') no-repeat 50% 50%/32px 32px;
        }

    </style>
</head>
<body>
    <div class="div1">文字水平居中</div>
    <h5>line-height</h5>
    <div class="div2">文字垂直居中</div>
    <div class="div2"><img src="2.png" alt=""></div>

    <h5>table-cell</h5>
    <div class="div3">文字垂直居中,这个更好些,内联元素</div>
    <div class="div3"><img src="2.png" alt=""></div>

    <h5>flex</h5>
    <div class="div4">
        flex布局垂直水平居中,下一个div换行显示。
    </div>
    <div class="div4">
        <img src="2.png" alt="">
    </div>
    <h5>background-image</h5>

    <div class="div5">

    </div>

</body>
</html>

演示地址:
http://xhope.top/samples/html/center_middle.html