不定宽高的div水平、垂直居中问题

HTML代码如下:

<div id="box">
  <div id="content"></div>
</div>

方法一(最佳兼容,IE7以上都可以):

    #box {
        width: 100px;
        height: 100px;
        position: relative;
    }

    #content {
        width: 50px;
        height: 50px;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
    }

方式二(实现最佳):

    #box {
        width: 100px;
        height: 100px;
        position: relative;
    }

    #content {
        position: absolute;
        width: 50px;
        height: 50px;
        left: 50%;
        top: 50%;
        -webkit-transform: translateX(-50%) translateY(-50%);
        transform: translateX(-50%) translateY(-50%);
    }

方法三(代码最简单):

    #box {
        width: 100%;
        height: 100%;
        display: -webkit-flex;
        display: flex;
        justify-content: center;
        align-items: center;
    } 

猜你喜欢

转载自www.cnblogs.com/johnjackson/p/10872591.html