子盒子在父盒子中实现水平垂直居中的方法

155 阅读1分钟

一、利用定位和margin实现

1.子绝父相(给父盒子添加相对定位(position: relative;),再给子盒子添加绝对定位(position: absolute;))。

.father {
            position: relative;
            width: 500px;
            height: 600px;
            background-color: pink;
	}
.son {
	position: absolute;
	width: 200px;
	height: 300px;
	background-color: skyblue;
     }

image.png

2.子盒子的top值和left值都设为50%。

.father {
            position: relative;
            width: 500px;
            height: 600px;
            background-color: pink;
	}
.son {
	position: absolute;
        top: 50%;
        left:50%;
	width: 200px;
	height: 300px;
	background-color: skyblue;
     }

image.png

3.子盒子的margin-top的值设为负的自身高度的一半,margin-left的值设为负的自身宽度的一半。

.father {
            position: relative;
            width: 500px;
            height: 600px;
            background-color: pink;
	}
.son {
	position: absolute;
        top: 50%;
        left: 50%;
	width: 200px;
	height: 300px;
        margin-top: -150px;
        margin-left: -100px;
	background-color: skyblue;
     }

image.png

二、利用定位和transform: translate();属性实现

前两步和利用定位和margin实现相同

3.子盒子添加transform: translate();属性,两个值都设为-50%即可。

.father {
            position: relative;
            width: 500px;
            height: 600px;
            background-color: pink;
	}
.son {
	position: absolute;
        top: 50%;
        left: 50%;
	width: 200px;
	height: 300px;
        transform: translate(-50%, -50%);
	background-color: skyblue;
     }

image.png

三、利用flex实现

  1. 父盒子添加display:flex;
  2. 再添加主轴对齐方式为居中:justify-content: center;
  3. 侧轴对齐方式为居中:align-items: center;
.father {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 500px;
            height: 600px;
            background-color: pink;
	}
.son {
	width: 200px;
	height: 300px;
	background-color: skyblue;
     }

image.png

学习笔记,有不对的地方望指正,感谢!