HTML 高度不祥的情况下自动水平垂直居中

内容比较简单就不说太多废话了,我们先看下效果图,如果不是自己需要的可以直接跳过

效果图

缩放前

缩放后


html部分

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" content="text/html">
    <title></title>
</head>
<body>
<div>
    <div class="layout">
        <div class="middle">
            <div class="font-layout">
                <div class="font-out">
                    <div class="font-inner"><input/></div>
                </div>
            </div>
        </div>
        <div class="left">
            <div class="font-demo">
                <div class="font-out">
                    <div class="font-inner" style="color: red">demo</div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

        这部分没有什么特别的,主要关注带有'font'的div标签,我们主要看middle部分,我们可以看到在middle中有三层嵌套的div,至于为什么是三层我们继续往下看,看看css就会豁然开朗

CSS部分

        .layout {
            overflow: hidden;
            padding-left: 200px;

        }

        .middle {
            width: 100%;
            background-color: yellow;
            height: 200px;
            float: left;
        }

        .left {
            width: 200px;
            background-color: #20A0FF;
            height: 200px;
            margin-left: -100%;
            float: left;
            position: relative;
            left: -200px;
        }

        .font-inner {
            background-color: #0bb20c;
            width: 35%;
            text-align: center;
            margin: 0 auto;
            font-size: 16px;
            line-height: 4;

        }

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

        .font-layout {
            text-align: center;
            display: table;
            width: 100%;
            height: 100%;
        }

        .font-demo {
            background-color: #0c3d5d;
            height: 100%;
            width: 100%;
            display: table;

        }

         这里也比较杂,我们主要关注.font-layout .font-out .font-inner三个class 。

                font-layout主要做了两件事情:

                1.设置了 text-align:center,是为了让其子类文字水平居中

                2.设置了display:table是为了把div的性质从块级标签变为列表

                font-out也是做了两件事情:

                1.设置了display:table-cell 就是设置其为一个单元格子

                2.设置了vertical-align有了上一步的经验这部就很好理解了,为单元格设置属性,垂直居中属性vertical-align

                font-inner做了最后的两件事

                1.font-align设置文字为居中

                2.margin:0 auto设置左右居中

这样就可以实现水平垂直居中了












猜你喜欢

转载自blog.csdn.net/qin_shuo/article/details/80356208