css3实现水平垂直居中

 

1、transform实现居中(未设宽高

<div id="wrap">内容</div>
<style>
#wrap{
padding:50px;
background:red;
position:absolute;
top:50%;
left:50%;
-webkit-transform:translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
transform:translate(-50%,-50%);
}
</style>

 

2、margin:auto(固定宽高

<div class="div1">
        <div class="div2"></div>
    </div>

<style>
    *{
        padding:0px;
        margin:0px;
    }
    .div1{
        width:800px;
        height:600px;
        position: relative;
        border:1px solid #f00;
    }
    .div2{
        width:300px;
        height:200px;
        position: absolute;
        margin:auto;
        top:0px;
        bottom: 0px;
        left:0px;
        right:0px;
        background: pink
    }
 </style>

3、绝对定位(固定宽高

    <div class="div1">
        <div class="div2"></div>
    </div>


<style>
    *{
        padding:0px;
        margin:0px;
    }
    .div1{
        width:800px;
        height:600px;
        position: relative;
        border:1px solid #f00;
    }
    .div2{
        width:300px;
        height:200px;
        position: absolute;
        top:50%;
        left:50%;
        margin-left: -150px;
        margin-top: -100px;
        background: pink
    }
</style>

4、table-cell和vertical-align(固定宽高),但是这种方法会使父元素无法居中

<div class="div1">
     <div class="div2"></div>
</div>

<style>
        .div1{
            width:500px;
            height:500px;
            border:1px solid black;
            display:table-cell;
            vertical-align: middle;
            
        }
        .div2{
            background: yellow;
            width:300px;
            margin:auto;
        }
</style>

 

posted @ 2018-01-08 18:55  yewook  阅读(141)  评论(0编辑  收藏  举报