您的位置:首页 > 其它

使不知宽高的元素水平垂直居中的方法

2017-09-15 16:49 274 查看
       本文主要介绍如何使元素居中显示的几种方法,当然方法有很多,现在记录的不过是笔者目前能够想到的几种:定位、table-cell、增加空span、弹性盒模型。

       html样式如下:

<div class="box">
<div class="box1"></div>
</div>
     css样式如下:

.box{
width:600px;
height:600px;}


    类名为.box1的div宽高未定。

   方法一(定位)

.box{
width:600px;
height:600px;
position:relative;
}
.box1{
position:absolute;
left:50%;
top:50%;
transfrom:translate(-50%,-50%);
}
  方法二(table-cell)
.box{
width:600px;
height:600px;
display:table-cell;
text-align:center;
vertical-align:middle;
}
.box1{
display:inline-block;
vertical-align:top;
}
 方法三(给box中增加一个空span)

<div class="box">
<span></span>
<div class="box1"></div>
</div>

.box{
width:600px;
height:600px;
}
.box span{
display:inline-block;
vertical-align:middle;
height:100%;
}
.box1{
display:inline-block;
vertical-align:middle;
}


   方法四(弹性盒模型)

.box{
width:600px;
height:600px;
display:flex;
justify-content:center;
align-items:center;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: