【面试题】div水平垂直居中

有一个 div#wrapper 元素,高、宽度都未知。它其中有一个宽高都为 100px 的 div#box 元素,请你完成 CSS,使得 div#box 在 div#wrapper 内水平、垂直方向居中。

解法1
    #wrapper{
        display: flex;
        justify-content: center;
        align-items: center;
    }
    #box{
        width: 100px;
        height: 100px;
        background-color: red;
    }
解法2
    #wrapper {
      position: relative; 
    }
    #box {
      width: 100px;
      height: 100px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
解法3
    #wrapper{
        position: relative;
    }
    #box{
        width: 100px;
        height: 100px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -50px;
        margin-left: -50px;
    }
解法4
    #wrapper{
        position: relative;
    }
    #box{
        width: 100px;
        height: 100px;
        position: absolute;
        left: calc(50% - 50px);
        top: calc(50% - 50px);
    }
解法5
    #wrapper{
        position: relative;
    }
    #box{
        width: 100px;
        height: 100px;
        position: absolute;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;
        margin: auto;
    }
解法6
    #wrapper{
        display: flex;
        align-items: center;
    }
    #box{
        width: 100px;
        height: 100px;
        margin: 0 auto;
    }

猜你喜欢

转载自blog.csdn.net/weixin_36270908/article/details/89711444