块元素居中的范例

范例1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div.box1{
             300px;
            height: 300px;
            background-color: lime;
            /* 设置为表格内的元素*/
            display: table-cell;
            /* 垂直居中 */
            vertical-align: middle;
        }
        div.box2{
             100px;
            height: 100px;
            background-color: peru;
            /* 让文本元素水平居中 */
            text-align: center;
            /* 让块元素居中 */
            margin: 0 auto;
            
        }
    </style>
</head>
<body>
    <div class="box1">
        <div class="box2">center</div>
    </div>
</body>
</html>
范例2:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div.box{
            800px;
            height: 800px;
            border: 2px solid red;
            /* 设置块元素为表格的列td元素 */
            display:table-cell;
            /* 让表格内的块元素设置为垂直居中 */
            vertical-align: middle;
    
        }
        div.box1{
            background-color: chartreuse;
             100px;
            height: 100px;
            /* 设置文字垂直居中(行高和块元素高度一致即可)*/
            line-height: 100px;
            /* 设置文字水平居中 */
            text-align: center;
            font-size: 50px;
            /* 设置块元素为水平居中 */
            margin: 0 auto;

        }
    </style>
</head>
<body>
    <div class="box">
        <div class="box1">1</div>
    </div>
</body>
</html>
范例3 利用弹性盒子flex
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        ul{
            border: 2px red solid;
             300px;
            height: 300px;
            /* 设置此元素为弹性容器 */
            display: flex;
            /* 设置弹性容器内的弹性元素沿辅轴居中排列 */
            align-items: center;
            /* 设置弹性容器内弹性元素沿主轴居中排列 */
            justify-content: center;

        }
       li{
           background-color: blue;
           100px;
           list-style: none;
           font-size: 50px;
           line-height: 50px;
           text-align: center;
      
        }
    </style>
</head>
<body>
    <ul class="box">
        <li class="box1">1</div>
    </ul>
</body>
</html>
原文地址:https://www.cnblogs.com/kukai/p/12305633.html