html----怎样实现元素的垂直居中

1.使用弹性盒

  
//使用弹性盒
  #box {
      width: 200px;
      height: 400px;
      background: lightblue;
      display: flex;
      align-items: center;

    }

    .con1 {
      width: 100px;
      height: 100px;
      background: lightpink;
    }

2.使用   绝对定位  + transform

<style>
    #box {
      width: 200px;
      height: 400px;
      background: lightblue;
      position: relative;

    }

    .con1 {
      width: 100px;
      height: 100px;
      background: lightpink;
      position: absolute;
      top: 50%;
      transform: translate(0, -50%);
    }
  </style>

3.使用绝对定位 + margin:auto

 <style>
    #box {
      width: 200px;
      height: 400px;
      background: lightblue;
      position: relative;
    }

    .con1 {
      width: 100px;
      height: 100px;
      background: lightpink;
      position: absolute;
      top: 0;
      bottom: 0;
      margin: auto;
    }
  </style>

猜你喜欢

转载自www.cnblogs.com/SRH151219/p/10401430.html
今日推荐