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

相关文章
相关标签/搜索