1. 程式人生 > >用 CSS 和 JS 實現元素的水平垂直居中

用 CSS 和 JS 實現元素的水平垂直居中

一、CSS 實現(2種方法)

方法1:已知要居中元素的寬高

   .d1{
        width:200px;
        height:200px;
        background-color:red;
        position:absolute;
        top:50%;
        left:50%;
        margin-top: -100px;
        margin-left: -100px;
    }
方法2:未知要居中元素的寬高(移動端建議這麼做)
      .d1{
            width:200px;
            height:200px;
            background-color:red;
            position:absolute;
            top:50%;
            left:50%;
            transform:translate(-50%,-50%);
            -webkit-transform:translate(-50%,-50%);
            -ms-transform:translate(-50%,-50%);
            -moz-transform:translate(-50%,-50%);
            -o-transform:translate(-50%,-50%);
        }
二、JS 實現
    function middle(){
        //獲取螢幕的高度
        var heightBig=window.innerHeight;
        //獲取元素的高度
        var d1=document.querySelector(".d1");
        var heightSmall=parseFloat(window.getComputedStyle(d1).height);
        d1.style.margin=(heightBig-heightSmall)/2+"px auto";
    }
    middle();
    window.onresize=middle;