div垂直居中知幾種?

html結構:實現box在wrap中垂直居中html

<div class="wrap">
    <div class="box"></div>
  </div>

方法一 flex彈性盒子實現flex

.wrap {
    display: flex;
    align-items: center;
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
  }
  .box {
    width:100px;
    height: 100px;
    background: red;
  }

方法二 relative和absolute實現code

.wrap {
    position: relative;
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
  }
  .box {
    position: absolute;
    top: 50%;
    margin-top: -50px;
    width:100px;
    height: 100px;
    background: red;
  }

方法三orm

.wrap {
    position: relative;
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
  }
  .box {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
    width:100px;
    height: 100px;
    background: red;
  }

方法四htm

.wrap {
    position: relative;
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
  }
  .box {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width:100px;
    height: 100px;
    background: red;
  }

方法2-4 都是相對定位和絕對定位配合實現, 可是方式略有不一樣圖片

方法五 table-cell和vertical-align實現it

.wrap {
    display: table-cell;
    vertical-align: middle;
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
  }
  .box {
    width:100px;
    height: 100px;
    background: red;
  }

因爲上傳圖片總是報錯,後面會把圖片加上io

相關文章
相關標籤/搜索