在网页布局中,将div元素居中对齐是一个常见且重要的任务,为此对其进行一个总结汇总。绝对不是为了方便cv大法

  1. 简单粗暴的 margin: auto

    .parent {
      position: relative;
      width: 300px;
      height: 300px;
      background-color: #f0f0f0;
    }
    
    .child {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      width: 100px;
      height: 100px; 
      margin: auto; 
      background-color: blue;
    }

    经典的“子绝父相”方法,缺点就是代码太长了

  2. Flexbox 大法好

    .flex-container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }

    只需设置父元素 display: flex 和 justify-content: center,子元素就乖乖居中了。

  3. 定位 + 变形

    .absolute-center {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    经典,也是最好用的一种方法

  4. Grid 布局绝技

    .grid-center {
      display: grid;
      place-items: center;
      height: 100vh;
    }

    代码最简洁,但要注意老旧浏览器的兼容性。