乐趣区

垂直居中的几种实现方式

相比较水平居中,垂直居中比较复杂点。尤其是在实际页面中,有很多特殊的场景,导致水平居中实现起来比较麻烦。这篇文章旨在纪录一些我知道的居中方式。以一道经典面试题为例:一个 200*200 的 div 在一个 div 水平垂直居中,用 css 实现。

首先定义元素

<!--dom 层:和垂直居中无关的样式直接定义在 style 里。-->
<body>
    <div class="margin" style="width: 500px;height: 500px;background-color: aqua">
        <div class="center" style="width: 200px;height: 200px;background-color: antiquewhite"></div>
    </div>
</body> 

1. 百分比的方式

缺点:必须知道居中元素的实际大小。根据实际大小用 margin 进行调整,因为 top,left 是以元素的上边框进行计算的。

<style>
    .center {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -100px;
      margin-left: -100px;
    }
    
    .margin{position: relative;    // 外层元素必须定义为 relative,否则是相对整个屏幕水平垂直居中}
</style> 

2. 百分比结合 transform

优点:利用 transform 改良上面那种必须知道元素大小的限制。

<style>
    .center{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    .margin{position: relative;}
</style> 

3.flex 布局

Flex 布局 (弹性布局),作为 css3 新增的布局方式,能很好的支持不同的屏幕大小,绝对是现在的前端工程师必备技能。

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

4.flex 布局结合 margin

    .margin{display: flex;}
        
    .center{margin: auto;}

5. 绝对定位和 0

    .margin{position: relative;}

    .center{
            overflow: auto;
            margin: auto;
            position: absolute;
            top: 0; left: 0; bottom: 0; right: 0;
       }
退出移动版