如何实现一个未知宽高元素的水平垂直居中?

以下是实现未知宽高元素水平垂直居中的三个方法:

方法1:通过定位和transform属性来实现

html:

<div class="parent">
    <div class="children">实现未知宽高元素垂直居中的方法1:通过定位和transform来实现</div>
</div>

css:

    <style>
        .parent{
            width:100%;
            height:400px;
            background:#666;
            position:relative;
        }
        .children{
            position:absolute;
            top:50%;
            left:50%;
            background:red;
            transform:translate(-50%,-50%);
        }
    </style>

方法2:通过利用flex布局

html:

<div class="parent">
    <div class="children">实现未知宽高元素的水平垂直居中方法2:主要是利用flex布局来实现</div>
</div>

css:

    <style>
        .parent{
            width:100%;
            height:400px;
            background:#666;
            display:flex;
            align-items:center;
            justify-content:center;
        }
        .children{
            background:red;
        }
    </style>

方法3:通过table属性

html:

<div class="parent">
    <div class="children">实现未知宽高元素垂直水平居中,主要原理是将父元素设置为table,子元素设置为table-cell,利用table属性</div>
</div>

css:

    <style>
        .parent{
            display:table;
            width:100%;
            height:400px;
            background:#666;
        }
        .children{
            display:table-cell;
            vertical-align:middle;
            text-align:center;
            background:red;
        }
    </style>
关于css这方面的知识也是很多,张鑫旭大神对这方面有很深入的研究,自己有时间也要多多研究,继续加油!

猜你喜欢

转载自blog.csdn.net/tozeroblog/article/details/79943579