css 垂直居中的各种方法

纯靠css实现的垂直居中


本文共用的html代码

<div class="box">
    <div class="contend">垂直居中div>
div>

table-cell 方式

.box{
    display: table-cell;
    vertical-align: middle;
    border: 1px solid #000;
    width: 200px;
    height: 200px;
    text-align: center;
}
 .contend{
    width: 100px;
    margin: 0 auto;
    border: 1px solid #000;
}

flex方法

.box{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 200px;
    border: 1px solid #000;
}
.contend{
    width: 100px;
    border: 1px solid #000;
    text-align: center;
}

绝对定位加负margin

.box{
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid #000;
   }
.contend{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
    border: 1px solid #000;
    text-align: center;
    width: 100px;
    height: 100px;
    line-height: 100px;
}

绝对定位并且各方向为0, margin为auto

.box{
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid #000;
}
.contend{
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    line-height: 100px;
    border: 1px solid #000;
}

这种方法跟上面的有些类似,但是这里是通过margin:autotop,left,right,bottom都设置为0,实现居中。不过这里得确定内部元素的高度。


CSS3的transform配合绝对定位

.box{
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid #000;
}
.contend{
    position: absolute;
    top: 50%;left: 50%;
    transform: translate(-50%,-50%);
    width: 100px;
    height: 100px;
    line-height: 100px;
    border: 1px solid #000;
}

display:inline-block, 通过:after来占位

.box{
     width: 200px;
     height: 200px;
     border: 1px solid #000;
     text-align: center;
 }
 .contend{
     display: inline-block;
     vertical-align: middle;
     width: 100px;
     height: 100px;
     line-height: 100px;
     border: 1px solid #000;
 }
 .box:after{
     content: '';
     width: 0;
     height: 100%;
     display: inline-block;
     vertical-align: middle;
 }

你可能感兴趣的:(经验总结)