如何实现div盒子水平垂直居中

关于如何使一个小盒子在大盒子中水平垂直居中有很多方法,下面将列举常用的几种:
实现效果

html 代码

<div class="parent">
    <div class="child">DEMO</div>
</div>

公共css样式

.parent{
    width:200px;height:300px;
    background:#ddd;
    }
.child{
    background:#666;
    color:#fff;
    }

(1)方法一:

设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子的居中;

.parent {
         position:relative;
        }
.child {
         position: absolute;
         margin: auto;
         top: 0;
         left: 0;
         right: 0;
         bottom: 0;
       }

(2)方法二 :定位+位移

使用子绝父相的定位方式,无须知道盒子自身的高度,使用范围较广

.parent{
    position: relative; 
    }
.child{
    position: absolute;
    left: 50%;  /* 父盒子宽度的50% */
    top: 50%;   /* 父盒子高度的50% */
    transform: translate(-50%,-50%);    /* 子盒子自身宽高的50% */   
    }

(2)方法三:table-cell+inline-block

将父盒子设置为table-cell(能够使元素呈单元格的样式显示),并设置text-align: center(使内容水平居中);vertical-align: middle(使内容垂直居中);。子盒子设置为inline-block可以使其内容变为文本格式,也可设置宽高;

.parent{
    display: table-cell;    /*使标签元素以表格单元格的形式呈现*/
    text-align: center;   /* 水平居中*/
    vertical-align: middle; /* 垂直居中 */
    }
.child{
    display: inline-block;  /* 将子盒子设置为行内块级(文本格式)*/
    }

(3)方法四:弹性盒子

使用弹性盒子的时候需要给父级设置display:flex;在父元素上设置水平与垂直方向上的排列方式即可;
该方法不需要设置子元素。

.parent{
    display: flex;
    justify-content: center;    /* 水平方向 居中*/ 
    align-items: center;        /* 垂直方向 居中*/
    }

总结:

以上几种方式推荐使用弹性盒子,因为在使用定位的时候会使元素脱离文档流出现撑不起父盒子的问题,而在弹性盒子中不会出现这样的问题,而且利用弹性盒子还能解决其他的问题。

猜你喜欢

转载自blog.csdn.net/weixin_42331327/article/details/80853935