css实现垂直水平居中

221 阅读1分钟
<div id="parent">
  <div id="child">要在parent里居中的方块</div>
</div>

一.内部盒子大小不固定

/* 方法一:通过flex */
#parent{
    display:flex; /* flex布局 */
    align-items: center; /* 侧轴方向居中(默认纵向) */
    justify-content: center; /* 主轴方向居中(默认横向) */
    width:500px; /* 随便给的宽度 */
    height:500px; /* 随便给的高度 */
}
#child{
    /* 不需要知道宽高 */
}
/* 方法二:通过position和transform */
#parent{
    position:relative; /* 相对定位 */
    width:500px; /* 随便给的宽度 */
    height:500px; /* 随便给的高度 */
}
#child{
    /* 主要代码在这里 */
    position:absolute; /* 绝对定位 */
    top:50%; 
    left:50%; /* 定位之后,图片的左上角位于父盒子中心 */
    transform:translate(-50%,-50%); /* 向左上平移半个盒子的距离,使盒子中心位于父盒子中心 */
}

二.内部盒子大小固定

/* 方法二:通过position和transform */
#parent{
    position:relative; /* 相对定位 */
    width:500px; /* 随便给的宽度 */
    height:500px; /* 随便给的高度 */
}
#child{
    /* 主要代码在这里 */
    position:absolute; /* 绝对定位 */
    top:0; 
    left:0;
    right:0;
    bottom:0; /* 上下左右定位距离都设置为0 */
    width:100px;
    height:100px; /* 需要有固定的大小 */
    margin:auto; 
}