实现子盒子在父盒子水平垂直居中的三种方式

140 阅读1分钟

1.利用定位子绝父相+外边距margin:
* { margin: 0; padding: 0; } .father { /* 父盒子相对定位 / position: relative; width: 800px; height: 600px; background-color: pink; } .son { / 子盒子绝对定位 / position: absolute; / 子盒子往下走父盒子一半的高度 / top: 50%; / 子盒子往右走父盒子一半的宽度 / left: 50%; / 子盒子往左走自身宽度的一半 / margin-left: -100px; / 子盒子往上走自身高度的一半 */ margin-top: -100px; width: 200px; height: 200px; }

2.利用定位子绝父相+位移transform: <style> * { margin: 0; padding: 0; } .father { /* 父盒子相对定位 */ position: relative; width: 800px; height: 600px; background-color: pink; } .son { /* 子盒子绝对定位 */ position: absolute; /* 子盒子往下走父盒子一半的高度 */ top: 50%; /* 子盒子往右走父盒子一半的宽度 */ left: 50%; /* 使用位移属性往左/往上移动自身宽高的一半的距离, 优点在于不论父盒子和子盒子宽高如何变化,不用改变数值子盒子都在父盒子的正中间 */ transform: translate(-50%,-50%); width: 200px; height: 200px; background-color: red; }
  3.利用flex实现盒子居中:   
  <style>
    * {
        margin: 0;
        padding: 0;
    }
    .father {
        /* 先让父盒子变弹性容器,子盒子变弹性盒子 */
        display: flex;
        width: 800px;
        height: 600px;
        background-color: pink;
        /* 主轴居中 */
        justify-content: center;
        /* 侧轴居中 */
        align-items: center;
    }
    .son {
        width: 200px;
        height: 200px;
        background-color: red;
    }
</style>