一位初学者的第一篇博客:实现一个子盒子,在父盒子里面水平居中和垂直居中有哪些方法?

230 阅读1分钟

现阶段所学的一共有四种,都是使用定位方法来实现:

第一种:给父盒子设定相对定位,给子盒子设定绝定位。通过子盒子绝对定位上右下左都为0,margin为aoto的方式,对子盒子始终居中在父盒子上面。

/* 第一种 */
         /* .box .box2 {
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
            width: 200px;
            height: 200px;
            background-color: skyblue;

第二种:给父盒子设定相对定位, 给子盒子设定绝定位。通过变换位移的属性,translate自身百分比的特性:相对于自身的宽高进行位移的。优点为:不管父盒子和子盒子怎么变化,子盒子始终都居中于父盒子。

.box .box2 {
             position: absolute;
             width: 200px;
             height: 200px;
             top: 50%;
             left: 50%;
             transform: translate(-50%,-50%);
             background-color: purple;

第三种:也是利用translate自身的特性设定一个自身2/1的绝对尺寸数值,使子盒子居中在父盒子上,一般不常用。

.box .box2 {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -100px;
            margin-left: -100px;
            width: 200px;
            height: 200px;
            background-color: #000;
        } 

第四种:使用最初的学习方法,通过margin和pidding方式,将子盒子挤到父盒子居中的位置。肯定不会使用!就不在展示代码。

以上是一位初学者关于盒子居中的四种方法,有说的不对的地方,欢迎指正和点评!