不固定高度盒子垂直与水平居中

2018-05-22  本文已影响0人  CodeBub
<style>
<body>
    <div class="box">
        <div class="child"></div>
    </div>
</body>

如上述代码,box高度固定,而child盒子中的内如不固定,高度随内如变化,要是child在box中垂直水平都居中,在此为大家介绍如下三种方法:

1.通过display:table-cell;属性;

<style>
  .box{
            width:200px;
            height:200px;
            border:1px solid red;
            display:table-cell;
            text-align:center;
            vertical-align:middle;
        }
        .child{
            width: 100px;
            height: 100px;
            background-color: green;
            display:inline-block;
        }
</style>

2.通过定位position,注意,关键的child的margin:auto;一定不能忘记设置;

<style>
.box{
            width:200px;
            height:200px;
            border:1px solid red;
            position: relative;    
        }
        .child{
            width: 100px;
            height: 100px;
            background-color:green;
            position: absolute;
            top:0;
            bottom:0;
            left:0;
            right:0;
            margin:auto;
        }
</style>

3.通过position定位和 transform:translate(-50%,-50%);

.box{
            width:300px;
            height:200px;
            border:1px solid red;
            position: relative;    
        }
        .child{
            width: 150px;
            height: 100px;
            background-color: green;
            position: absolute;
            left:50%;
            top:50%;
            transform:translate(-50%,-50%); 
        }

当然通过flex盒子模型也是可是的,在此就不再给出代码演示,具体可以了解一下flex盒子模型

上一篇 下一篇

猜你喜欢

热点阅读