前端面试题合集 CSS篇---盒子垂直居中的方式有哪些?

163 阅读2分钟

前端面试题合集 CSS篇---垂直居中的方式

页面结构

// css样式  盒子最初
    <style>
    .father {
      width: 400px;
      height: 400px;
      background-color: #f2e0e0;
    }
    .son {
      width: 100px;
      height: 100px;
      background-color: #f29e9e;
    }
    </style>
    
// 盒子结构
    <body>
      <div class="father">
        <div class="son"></div>
      </div>
    </body>

image.png

方式一、flex布局(最常用)

给父元素加 display: flex; 使用align-items: center;justify-content: center;(取决于你是垂直居中还是水平居中)来实现子元素的垂直居中。这里就不过多介绍flex布局,后续会出一集关于flex的详解~

  <style>
    .father {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  </style>

image.png

方式二、利用定位 + transform

给父盒子添加相对定位,给子盒子添加绝对定位 子绝父相

  <style>
    .father {
      position: relative; /* 父元素相对定位 */
    }

    .son {
      position: absolute; /* 子元素绝对定位 */
      top: 50%;  
      left: 50%;
      transform: translate(-50%, -50%);
    }
  </style>

方式三、利用定位 + 负margin

  <style>
    .father {
      position: relative; /* 父元素相对定位 */
    }
    .son {
      position: absolute;   /* 子元素绝对定位 */
      top: 50%;
      left: 50%;
      margin-left: -50px;  /* 自身宽度的一半 */
      margin-top: -50px;   /* 自身高度的一半 */
  /* margin-left、margin-top 相当于设置自身中心点位置 等价于 transform: translate(-50%, -50%); */
    }
  </style>

方式四、利用定位 + margin:auto

  <style>
    .father {
      position: relative; /* 父元素相对定位 */
    }
    .son {
      position: absolute;   /* 子元素绝对定位 */
      top:0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
    }
  </style>

方式五、table-cell

  <style>
    .father {
      display: table-cell;     /* 转为 table-cell 显示模式 */
      vertical-align: middle;
      text-align: center;
    }
    .son {
      display: inline-block;    /* 转为行内块 */
    }
  </style>

方式六、grid布局 给子元素加

  <style>
    .father {
      display: grid;    /* 网格布局 给父盒子加   缺点:兼容不如flex */
      vertical-align: middle;
      text-align: center;
    }
    .son {
      align-self: center;    /* 给子元素加 */
      justify-self: center;
    }
  </style>

方式七、grid布局 给父元素加

  <style>
    .father {
      display: grid;      /* 网格布局 给父盒子加   缺点:兼容不如flex */
      align-content: space-around;
      justify-content: space-around;
    }
  </style>