1. 程式人生 > >css實現垂直水平居中的5種方法

css實現垂直水平居中的5種方法

進行 posit tran cto ans otto data -c ive

css實現垂直水平居中的5種方法

  1. 給父元素設置table-cell,text-align,vertical-align
#big{
        width: 200px;
        height: 200px;
        border:1px solid #000;
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
    #small{
        display: inline-block;
        width: 50px;
        height: 50px;
        background: yellow;
        vertical-align:middle;
    }
  1. 給子元素設置margin:auto
#big{
        width: 200px;
        height: 200px;
        border:1px solid #000;
        position: relative;
    }
    #small{
        display: inline-block;
        width: 50px;
        height: 50px;
        background: yellow;
        position: absolute;
        left:0;
        right:0;
        top:0;
        bottom:0;
        margin:auto;
    }
  1. 彈性盒
#big{
        width: 200px;
        height: 200px;
        border:1px solid #000;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    #small{
        display: inline-block;
        width: 50px;
        height: 50px;
        background: yellow;
    }
  1. 利用translate實現,先進行絕對定位,然後通過translate讓它自身往回移動50%
#big{
        width: 200px;
        height: 200px;
        border:1px solid #000;
        position: relative;
    }
    #small{
        display: inline-block;
        width: 50px;
        height: 50px;
        background: yellow;
        position:absolute;
        top:50%;
        left:50%;
        transform:translate(-50%,-50%);
    }
  1. 通過新創建一個元素,設置高為父元素的高,讓div以這個元素來執行vertical-align
#big{
        width: 200px;
        height: 200px;
        border:1px solid #000;
        text-align: center;
    }
    #small{
        display: inline-block;
        width: 50px;
        height: 50px;
        background: yellow;
        vertical-align: middle;
    }
    span{
        display: inline-block;
        width: 0;
        height: 100%;
        background: red;
        vertical-align: middle; 
    }
    </style>
</head>
<body>
    <div id="big">
        <div id="small">
        </div>
        <span></span>
    </div>
</body>

css實現垂直水平居中的5種方法