【study】盒子水平居中的六种方法

439 阅读1分钟

1.flex方法

    <div class="box" id="box"> 
        <div class="one"></div>
    </div>
      .box{
           width:200px;
           height: 200px;
           border: 1px solid green;
           display: flex;
           align-items: center;
           justify-content: center;
       }
       .one{
           width: 50px;
           height: 50px;
           background-color: pink;
       }

2.定位的3种方法

(1)父相子绝+transform

   <div class="box" id="box"> 
         <div class="one"></div>
   </div>
    .box{
            width:200px;
            height: 200px;
            border: 1px solid green;
            position: relative;
        }
     .one{
            width: 50px;
            height: 50px;
            background-color: pink;
            position: absolute;
            top:50%;
            left:50%;
            transform: translate(-50%,-50%);
        }

(2)父相子绝+margin-left+margin-top

   <div class="box" id="box"> 
         <div class="one"></div>
   </div>
 .box {
            width:200px;
            height: 200px;
            border: 1px solid green;
            position: relative;
        }
   .one{
            width: 50px;
            height: 50px;
            background-color: pink;
            position: absolute;
            top:50%;
            left:50%;
            margin-left:-25px;
            margin-top:-25px;
        }

(3)父相子绝+margin:auto

  <div class="box" id="box"> 
        <div class="one"></div>
  </div>
   .box{
           width:200px;
           height: 200px;
           border: 1px solid green;
           position: relative;
       }
       .one{
           width: 50px;
           height: 50px;
           background-color: pink;
           position: absolute;
           left:0;
           right: 0;
           top:0;
           bottom:0;
           margin:auto;
       }

3.table-cell(要求父级有固定宽高,百分比不算)

<div class="box" id="box"> 
         <div class="one"></div>
  </div>
  .box{
            width:200px;
            height: 200px;
            border: 1px solid green;
            display:table-cell;
            text-align:center;
            vertical-align: middle;
        }
    .one{
            width: 50px;
            height: 50px;
            display:inline-block;
            background-color: pink;
        }

4.js方法(box相对于页面居中)

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