未知宽高的元素水平垂直居中方法总结

1.父元素设置display:table;子元素设置display:table-cell;

缺点:IE7不支持,而且子元素会填满父元素,不建议使用

2.使用css3 transform:translate(-50%; -50%)

缺点:兼容性不好,IE9+

3.使用flex布局

缺点:兼容性不好,IE9+

4.利用伪类元素

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>未知宽高元素水平垂直居中</title>
</head>
<style>

    .outer1{
        display: table;
        height:300px;
        width: 300px;
        background-color: #ccc;
        float:left;
        margin:20px;
    }
    .inner1{
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        color: #fff;
        font-size: 16px;
        border:1px solid red;
    }
    .outer2{
        height:300px;
        width: 300px;
        text-align: center;
        background-color: #ccc;
        position:relative;
        float:left;
        margin:20px;
    }

    .inner2{
        position: absolute;
        top: 50%;
        left: 50%;
        transform:translate(-50%,-50%);
    }
    .outer3{
        display: flex;
        justify-content: center;
        align-items: center;
        width: 300px;
        height:300px;
        background: #ccc;
        float:left;
        margin:20px;
    }
    .outer4{
        text-align: center;
        width: 300px;
        height:300px;
        background: #ccc;
        float:left;
        margin:20px;
    }
    .outer4:before{
        content:"";
        display: inline-block;
        vertical-align: middle;
        width: 0;
        height: 100%;
    }
    .inner4{
        display: inline-block;
    }

</style>
<body>
<div class="outer1">
    <div class="inner1">table-cell 实现</div>
</div>
<div class="outer2">
    <div class="inner2">css3</div>
</div>
<div class="outer3">
    <div class="inner3">flex布局</div>
</div>
<div class="outer4">
    <div class="inner4">伪类元素</div>
</div>
</body>
</html>

效果:

 

posted @ 2017-08-27 23:27  yaokunlun  阅读(363)  评论(0编辑  收藏  举报