css水平垂直居中

水平垂直居中包括几种,下面我就自己所知道的进行详细的讲解,希望对您有收获

html代码:

 <div class="wrapper">

     <div class="son">我是子盒子</div>

  </div>

css代码:

 1,文字水平垂直居中

       .son {
                     200px;
                    height: 200px;
                    text-align: center;
                    line-height: 200px; //行高为盒子的高度
                }

      

  2,块状元素水平居中

     .son {
                    margin: 0px auto;
                }

  3,块状元素水平垂直居中 

第一种方法:

.son{

weight:200px;

height:200px;

<!--把元素变成定位元素-->

position:absolute;

<!--设置元素的定位位置,距离上、左都为50%-->

left:50%;

top:50%;

<!--设置元素的左外边距、上外边距为宽高的负1/2-->

margin-left:-100px;

margin-top:-100px;

}

*兼容性好;缺点:必须知道元素的宽高

-------------

第二种方法:

.son{

weight:200px;

height:200px;

<!--把元素变成定位元素-->

position:absolute;

<!--设置元素的定位位置,距离上、左都为50%-->

left:50%;

top:50%;

<!--设置元素的相对于自身的偏移度为负50%(也就是元素自身尺寸的一半)-->

transform:translate(-50%,-50%);

}

*这是css3里的样式;缺点:兼容性不好,只支持IE9+的浏览器 

---------------

第三种方法

.son{

weight:200px;

height:200px;

<!--把元素变成定位元素-->

position:absolute;

<!--设置元素的定位位置,距离上、下、左、右都为0-->

left:0;

right:0;

top:0;

bottom:0;

<!--设置元素的margin样式值为 auto-->

margin:auto;

}

*兼容性较好,缺点:不支持IE7以下的浏览器

看繁华,听风落
原文地址:https://www.cnblogs.com/lgnblog/p/9994986.html