未知宽高的div水平垂直居中

未知宽度的div使内容水平垂直居中

方法一:使用display:flex;justify-content:center;align-items: center;属性

代码如下:
<style>
#box{
display: flex;
justify-content:center;
align-items: center;
height: 500px;
}
</style>
<div id="box">
水平垂直居中
</div>

方法二:使用transform: translate(-50%, -50%);属性

代码如下:
<style>
  #box{
    position: absolute;
    top:50%;
    left:50%;
    transform: translate(-50%,-50%);
  }
</style>
<div id="box">
  水平垂直居中
</div>

方法三:使用display:table属性

代码如下:
<style>
.parent{
display: table;
width: 300px;
height: 300px;
background-color: #f00;
}
.son{
display: table-cell;
vertical-align: middle;
text-align: center;
color:blue;
}
</style>
<div class="parent">
<div class="son">水平垂直居中</div>
</div>

猜你喜欢

转载自www.cnblogs.com/lingdu87/p/9152937.html