css实现垂直水平居中的方法

2017-07-30  本文已影响72人  Aleph_Zheng

网上这种类型的文章数之不尽,作为个人学习的一个整理,仅供参考,欢迎斧正。
兼容性方面请参考http://caniuse.com/

方法一:table-cell实现垂直居中

缺点:margin无效(我给所有元素设置了margin:auto的)
优点:兼容IE8以上浏览器,动态设置居中,不需要知道宽高

//html
<div class="ct1 ct">
        <div class="box1 box"></div>
</div>
//css
.ct {
        width: 300px;
        height: 300px;
        border: 1px solid red;
        margin: 0 auto;
    }
 .box {
        width: 80px;
        height: 80px;
        background: lightblue;
    }
.ct1 {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
.box1 {
        display: inline-block;//为了使text-align生效
    }

效果:

image.png

方法二:父元素设置相对定位,子元素绝对定位。

缺点:
1、要么必须知道宽高,手动设置偏移量(margin量)。要么用css3的tranform(IE11以上,兼容性不好)
2、子元素高于父元素会超出父元素直接显示,不会出现滚动条
优点:
影响小,写法固定且简便

//html
 <div class="ct2 ct">
        <div class="box2 box"></div>
 </div>

//css
.ct {
    width: 300px;
    height: 300px;
    border: 1px solid red;
    margin: 0 auto;
}
.box {
    width: 80px;
    height: 80px;
    background: lightblue;
}
.ct2 {
     position: relative;
}

.box2 {
     position: absolute;
     left: 50%;
     top: 50%;
     transform: translate(-50%, -50%);
 }

效果:


image.png

方法三:display:flex

缺点:对IE兼容性不好,IE11才部分支持
优点:用起来又简单又方便,很爽啊有木有~~(ノ´▽`)ノ♪

//html
<div class="ct3 ct">
        <div class="box3 box"></div>
</div>

//css
.ct {
    width: 300px;
    height: 300px;
    border: 1px solid red;
    margin: 0 auto;
}
.box {
    width: 80px;
    height: 80px;
    background: lightblue;
}
.ct3{
    display: flex;
    align-items: center;
    justify-content: center;
 }
image.png

方法四:定位+偏移0+margin:auto

//html
    <div class="ct4 ct">
        <div class="box4 box"></div>
    </div>
//css
    .ct4{
        position: relative;
    }
    .box4{
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
    }
image.png

你问我最喜欢用哪个?不考虑兼容性的情况下当然是flexbox啊(◕ᴗ◕✿)

上一篇 下一篇

猜你喜欢

热点阅读