div水平垂直居中的方法

1.盒子没有固定的宽和高

   方法1.Transforms变形

         这是比较简单的方法,不仅能实现绝对居中的效果,也支持联合可变高度方式使用。内容块定义transform: translate(-50%,-50%)  必须加上top: 50%; left: 50%。但是不兼容IE8以及以下,可能干扰其他transform效果,某些情形下会出现文本或元素边界渲染模糊的现象。具体代码如下:

   .wrapper {

       padding: 20px;
            background: orange;
            color: #fff;
            position: absolute;
            top: 50%;
            left: 50%;
            border-radius: 5px;
            -webkit-transform: translate(-50%, -50%);
            -moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);

        }

         <div class="wrapper">我不知道我的宽度和高是多少,我要实现水平垂直居中。</div>

   方法2.在父级元素上面加上3句话,就可以实现子元素水平垂直居中     

     这种方法只需在父级加上justify-content: center;align-items: center;display: -webkit-flex就可以,但是这种方法兼容性也不好。

  .wrapper {
            width: 500px;
            height: 300px;
            background: orange;
            color: #fff;
            /*只需要在父元素上加这三句*/
            justify-content: center; /*子元素水平居中*/
            align-items: center; /*子元素垂直居中*/
            display: -webkit-flex;
        }
  <div class="wrapper">我不知道我的宽度和高是多少,我要实现水平垂直居中。</div>

  

2.盒子有固定的宽和高

  方法1、margin 负间距,兼容性好

          此方案代码关键点:

     1.必需知道该div的宽度和高度。

          2.然后设置位置为绝对位置。

      3.距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指页面窗口的宽度和高度的50%。

    4.最后将该div分别左移和上移,左移和上移的大小就是该DIV宽度和高度的一半。

   .wrapper {
      width: 400px;
      height: 18px;
      padding: 20px;
      background: orange;
      color: #fff;
      position: absolute;
      top:50%;
      left:50%;
      margin-top: -9px;
      margin-left: -200px;
  }

      <div class="wrapper">我知道我的宽度和高是多少,我要实现水平垂直居中。</div>

    方法2.margin:auto实现绝对定位元素的居中(此方法兼容ie8以上浏览器)

   此方案代码关键点:

    1、上下左右均0位置定位;

           2、margin: auto;

   .wrapper {
      width: 400px;
      height: 18px;
      padding:20px;
      background: orange;
      color: #fff;
      position: absolute;
      left:0;
      right:0;
      top: 0;
      bottom: 0;
      margin: auto;
    }

   <div class="wrapper">我知道我的宽度和高是多少,我要实现水平垂直居中。</div>

       

3.父级的高度根据子级的自适应,子级盒子垂直水平居中
  
使用display:table结合vertical-align:middle来实现,此方法只兼容IE8以上的浏览器
    此代码关键点:
    
  1.父级盒子设置display:table;
      2.子级盒子设置display:table-cell;text-align: center;vertical-align:middle;
     
#demo{

        display:table;
        width:500px;
        margin:10px auto;
        background:#eee;
      
}
      

      .box{
        width: 300px;
        height:100px;
        display:table-cell;
        text-align: center;
        vertical-align:middle;
      }

 

      <div id="demo">
        <div class="box">水平垂直居中的随意内容</div>
      </div>

 

 

 


    

 

posted @ 2017-04-17 14:59  小芳姑娘~~  阅读(166)  评论(0编辑  收藏  举报