css多种方法实现已知宽度和未知宽度的元素水平垂直居中

 
// html

<div class="box-wrapper">
    <div class="box">
        内部box
        <p>更多内容</p>
    </div>
</div>

//css
.box-wrapper{
    width: 100%;
height: 300px; border: 1px solid #f00;
.box{

}
}
 

1、已知box宽高

.box-wrapper{
    position: relative;
.box{ position: absolute; top: 50%; left: 50%;
width: 200px;
height: 100px; margin-top: -50px; margin-left: -100px; } }

2、未知box宽高

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

3、未知box宽高

.box-wrapper{
    display: flex;
    justify-content: center;
    align-items: center;
}

4、未知box宽高, 内容垂直居中

.box-wrapper {
  display: table-cell;
vertical-align: middle;
width: 400px;
text-align: center;
.box{
display: inline-block;
}
}

 

猜你喜欢

转载自www.cnblogs.com/wkyuan/p/11316183.html