CSS知识点

实现div盒子水平垂直居中的几种方式

  <body id="container">
      <div id="middle"></div>
  </body>

  <style>

    html,body {
      height:100%; /*  注意html不设置高度 body也就没有继承高度,就会随内容支撑高度

      overflow: hidden; */ //方式一

      margin:0;

      padding: 0;

    }

  </style>

  1.第一种方式元素已知宽度高度,绝对定位absolute+margin一半

  #middle {
    background: red;

     200px;

    height: 200px;

    position: absolute;

    top: 50%;

    left: 50%;

    margin-left: -100px;

    margin-top: -100px;

  }

  2. 第二种方式元素未知,绝对定位absolute+translate(平移一半)

  #middle {
    background: red;

     200px;

    height: 200px;

    position: absolute;

    top: 50%;

    left: 50%;

    transform: translate(-50%,-50%);

  }

  3. 第三种方式元素未知,绝对定位absolute+margin:auto

  #middle {
    background: red;

     200px;

    height: 200px;

    position: absolute;

    left: 0;

    right: 0;

    top: 0;

    bottom: 0;

    margin: auto;

  }

  4. 第二种方式元素未知,display:flex

  #container{

    display: flex;

    justify-content: center;

    align-items: center;

  }

原文地址:https://www.cnblogs.com/vofill/p/14801986.html