纯CSS实现元素垂直水平居中-非固定宽度

这里不讨论行内元素的居中!!

盒子垂直居中+水平居中的需求时经常遇到的,看到的较多实现逻辑是固定content-box的宽度,通过让margin-left和margin-top等于宽或高的负一半来实现,抑或不固定宽度,通过JS调整margin-left和margin-top的值,这俩种方法原理都一样。
而我接下来要讲的是content不定宽的情况下,CSS的源生实现。

利用table实现垂直水平居中

主要利用td的vertical-align: middle;属性实现垂直居中,当然你可以用display:table-cell;也可以得到一样的效果。配合margin: 0 auto;实现水平居中,支持IE 8+。
效果:https://codepen.io/FreadChen/…


<style>
  *{
    padding: 0;
    margin: 0;
  }
  html,body,.center-box{
    height: 100%;
    width:100%;
  }

  .center-box>tr>td{
    height: 100%;
    vertical-align: middle;
  }
 .content-box{
    margin: 0 auto;
    /*下面这段是非必须的代码,演示效果需要*/
    background: #1f2d3d;
    width: 200px;
    height: 200px;
  }
</style>
<body>
<table class="center-box">
  <tr>
    <td>
      <div class="content-box"></div>
    </td>
  </tr>
</table>
</body>

利用flex实现水平垂直居中

利用flex布局可以实现更多功能,这里利用了“justify-content”实现水平居中、“align-items”实现垂直居中,“flex: 0 0 auto;”让元素保持原来的宽高。这个技术的局限在于支持IE 10+。
了解Flex请戳:http://www.ruanyifeng.com/blo…
看效果请戳:https://codepen.io/FreadChen/…


<style>
  *{
    padding: 0;
    margin: 0;
  }
  html,body{
    height: 100%;
  }
  .center-box{
    display: -webkit-flex; /* Safari */
    display: flex;
    /* // 水平居中 */
    justify-content: center;
    /* // 垂直居中 */
    align-items: center;
    height: 100%;
    width: 100%;
  }
  .content-box{
    flex: 0 0 auto;
    width: 200px;
    height: 200px;
    background: #1f2d3d;
  }
</style>
<body>
<div class="center-box">
  <div class="content-box"></div>
</div>
</body>

利用position + transform实现垂直居中

利用position的绝对定位absolute(absolute的使用技巧自行了解)将left和top都设为50%;再利用transform: translate(-50%,-50%);来补偿元素宽高所带来的位置影响。该技巧支持IE9+。
看效果请戳:https://codepen.io/FreadChen/…


<style>
  *{
    padding: 0;
    margin: 0;
  }
  html,body,.center-box{
    height: 100%;
    width:100%;
  }

 .content-box{
    margin: 0 auto;
    /*下面这段是非必须的代码,演示效果需要*/
    background: #1f2d3d;
    width: 200px;
    height: 200px;
   position:absolute;
   left: 50%;
   top:50%;
   transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%); /* IE 9 */
-webkit-transform: translate(-50%,-50%); /* Safari and Chrome */
  }
</style>
<body>
<div class="content-box"></div>
</body>
    原文作者:SmartCoder
    原文地址: https://segmentfault.com/a/1190000014622339
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞