盒子垂直水平居中

一、定位 盒子寬高已知, position: absolute; left: 50%; top: 50%; margin-left:-自身一半寬度; margin-top: -自身一半高度;

二、table-cell佈局 父級 display: table-cell; vertical-align: middle;  子級 margin: 0 auto;

三、定位 + transform ; 適用於 子盒子 寬高不定時; (這裏是本人經常使用方法)
    
    position: relative / absolute;
    /*top和left偏移各爲50%*/
       top: 50%;
       left: 50%;
    /*translate(-50%,-50%) 偏移自身的寬和高的-50%*/
    transform: translate(-50%, -50%); 注意這裏啓動了3D硬件加速哦 會增長耗電量的 (至於何是3D加速 請看瀏覽器進程與線程篇)

四、flex 佈局
    父級: 
        /*flex 佈局*/
        display: flex;
        /*實現垂直居中*/
        align-items: center;
        /*實現水平居中*/
        justify-content: center;

再加一種水平方向上居中 :margin-left : 50% ; transform: translateX(-50%);







<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .box {
      width: 300px;
      height: 300px;
      background: silver;
      margin: 80px auto;
      display: flex;
      flex-direction: column;
      flex-wrap: nowrap;
      justify-content: space-between;
      align-items: center;
    }

    .top,
    .middle,
    .bottom {
      width: 100%;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
      align-items: center;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="top">
      <div class="left">1</div>
      <div class="center">2</div>
      <div class="right">3</div>
    </div>
    <div class="middle">
      <div class="left">4</div>
      <div class="center">5</div>
      <div class="right">6</div>
    </div>
    <div class="bottom">
      <div class="left">7</div>
      <div class="center">8</div>
      <div class="right">9</div>
    </div>
  </div>
</body>

</html>
相關文章
相關標籤/搜索