水平垂直居中的实现方式

315 阅读1分钟

已知大小

position: fixed | absolute; 都可以

margin

.wrap {
	position: fixed;
	margin-top: -100px;
	margin-left: -100px;
	top: 50%;
	left: 50%;
	width: 200px;
	height: 200px;
}
.wrap {
	position: absolute;
	margin: auto;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	width: 200px;
	height: 200px;
}

translate

.wrap {
	position: fixed;
	top: 50%;
	left: 50%;
	width: 200px;
	height: 200px;
	transform: translate(-100px, -100px);
}

未知大小

translate

.wrap {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

flex

.wrap {
    display: flex;
    align-items: center;
    justify-content: center;
}