1. 程式人生 > 實用技巧 >CSS 水平垂直居中

CSS 水平垂直居中

水平垂直居中

定位

1. 百分比, 知道具體寬高

讓盒子距離左上50%,然後向左上移動一半的距離

 #position1 {
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -25px;
        margin-left: -50px;
}
2. 自動,不知道具體寬高

不需要具體寬高,margin自動填充剩餘的空間

#position2 {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
 }
3. transform, translate, 不需要寬高

不需要寬高,translate(-50%,-50%)元素在水平方向和垂直方向同時移動,相容性不好

 #position3 {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
 }
4. JS, 不需要知道具體寬高

獲得父級和盒子元素的寬高,讓盒子絕對定位,並使其距離左上位置為剩餘空間的一半

let HTML = document.documentElement,
        winW = HTML.clientWidth,
        winH = HTML.clientHeight,
        box = document.getElementById("box"),
        boxW = box.offsetWidth,
        boxH = box.offsetHeight;
      box.style.position = "absolute";
      box.style.left = (winW - boxW) / 2 + "px";
      box.style.top = (winH - boxH) / 2 + "px";

flex彈性盒模型

5. flex

給父節點設定flex盒子,並讓他的子元素主軸交叉軸居中,不相容,移動端常用

 body {
        display: flex;
        justify-content: center;
        align-items: center;
}