CSS常见的水平垂直居中实现

70 阅读1分钟

flex布局

               .father {
			background-color: orange;
			height: 100px;
			width: 100px;
			display: flex;
			justify-content: center;
			align-items: center;
		}
		.son {
			background-color: red;
			height: 30px;
			width: 30px;
		} 

绝对定位 margin:auto

		.father {
			position: relative;
			background-color: orange;
			height: 100px;
			width: 100px;
		}

		.son {
			position: absolute;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			margin: auto;
			background-color: red;
			height: 30px;
			width: 30px;
		}

绝对定位 transform实现

		.father {
			position: relative;
			background-color: orange;
			height: 100px;
			width: 100px;
		}

		.son {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			background-color: red;
			height: 30px;
			width: 30px;
		}