纯css 无视宽高设置垂直水平居中

  1. flex的居中。(IE10+)
.parent {
	display: flex;
	justify-content: center;
	align-items: center;
}
复制代码

css

.parent {
	display: flex;
}
.child {
	margin: auto;
}

复制代码
  1. 先移动父级的50%,再利用 translate往回移动自身的50%。(IE9+)
.child {
	margin-top: 50%;
	margin-left: 50%;
	transform: translate(-50%,-50%);
}

复制代码

浏览器

.parent {
	position: relative;
}
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
}
复制代码
  1. 利用positionmargin。 (IE8+)
.parent {
	position: relative;
}
.child {
	position: absolute;
	top: 0;
	buttom:0;
	left: 0;
	roght: 0;
	margin: auto;
}
复制代码
  1. 经过display:table-cell来把.parent模拟成一个表格单元格,利用表格的居中特性。(IE8+)
.parent {
	display: table-cell;
	vertical-align: middle;
	text-align: center;
}
复制代码
  1. 利用 :after 伪选择器占位. (IE8+)
  • IE8的伪选择器要使用:after,更新版的浏览器能够使用 :after::after
.parent {
	text-align: center;
}

.child {
	display:inline-block;
	vertical-align: middle;
}
.parent:after {
	content: "";
	vertical-align: middle;
	height: 100%;
	display: inline-block;
}

复制代码
相关文章
相关标签/搜索