css居中方法详解

第一种居中方式:

使用margin:auto;

这应该是使用最多的居中方式了,但也有着局限性,居中的元素需要设置宽度,而且是块元素才行,并且只能实现水平居中,这个方法的原理是让浏览器自动去计算左右边距从而实现居中;

<div class="big">
    <div class="small"></div>
</div>
.big{
         200px;
        height: 100px;
        background: blue;

    }
    .small{
         50px;
        height: 50px;
        background: orange;
        margin: 0 auto;
    }

第二种居中方式:

使用text-align:center实现居中,这种居中方式对于容器内的图片,文字能够很方便的实现居中。直接给父元素设置text-align:center就行;

第三种居中方式:

利用table-cell实现居中,这种方法可以实现水平垂直居中,但是需要外套一层标签;IE8+有效

<div class="big">
        <div class="big-small">
            <div class="small"></div>
        </div>
    </div>
.big{
         200px;
        height: 100px;
        background: blue;
        display: table;

    }
    .big-small{
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
    .small{
         50px;
        height: 50px;
        background: orange;
        margin: 0 auto;
    }

第四种居中方式:

使用position:absolute居中;可以实现水平垂直居中;

浏览器兼容性好,但是必须显式声明外部容器元素的height;来看一下代码:

<div class="big">
        <div class="small"></div>
    </div>

.big{
        position: relative;
         200px;
        min-height: 100px;
        background: blue;
    }
    
    .small{
         50px;
        height: 50px;
        background: orange;
        position: absolute;
        top: 0;left: 0;bottom: 0;right: 0;margin: auto;
    }

第五种居中方式:

使用css translate居中,同样可以实现水平垂直居中;但是使用transform需要加前缀,只支持IE9+,外部容器需要设置高度,如果内容包含文字,文字可能出现模糊;

<div class="big">
        <div class="small"></div>
    </div>

.big{
        position: relative;
         200px;
        min-height: 100px;
        background: blue;
    }
    
    .small{
         50px;
        height: 50px;
        background: orange;
        position: absolute;
        transform: translate(-50%,-50%);
        top: 50%;left: 50%;
    }

这种方法实现的原理是:首先让需要居中的元素在容器内绝对定位,然后设置top:50%;left:50%;从而让元素距离顶部为容器的一半高度,距离左边为容器的宽度的一半,然后使用translate使元素向左向上偏移自身的宽高的一半实现居中;

第六种方式:

使用flexbox居中;给父容器设置display:flex;这种方法比较简单,而且新版本浏览器都支持。

<div class="big">
        <div class="small">我就是要这种</div>
    </div>

.big{
        position: relative;
         400px;
        height: 100px;
        background: blue;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    
    .small{
         100px;
        height: 50px;
        background: orange;
        
    }

第七种方式:

使用calc动态计算实现居中;同样可以实现水平垂直居中

.big{
        position: relative;
         400px;
        height: 100px;
        background: blue;
        
    }
    
    .small{
         40%;
        height: 50px;
        background: orange;
        position: absolute;
        top: calc(50% - 20%);
        left: calc(50% - 20%);   
    }

如果只有50%,内部元素的左上角在容器的中心,明显不符合,所以还要让元素向左向上移动自身的一半,从而实现居中。注意:calc(50% - 20%);当是一个计算式的时候,减号左右需要一个空格,否则无法识别哦;

参考博客:

http://www.75team.com/

原文地址:https://www.cnblogs.com/luxueping/p/5599965.html