Skip to content

居中

建议使用 5. translate

1. table-cell

css
.box1 {
	display: table-cell;
	vertical-align: middle;
	text-align: center;
}

优点

  1. 兼容性好。

  2. 不定宽高。

缺点

  1. html 层级多

2. display:flex

css
.box2 {
	display: flex;
	justify-content: center;
	align-items: Center;
}

3. 绝对定位和负边距

css
.box3 {
	position: relative;
}

.box3 span {
	position: absolute;
	width: 100px;
	height: 50px;
	top: 50%;
	left: 50%;
	margin-left: -50px;
	margin-top: -25px;
	text-align: center;
}

缺点

  1. 定宽高且不支持百分比

4. 绝对定位和 0

css
.box4 span {
	width: 50%;
	height: 50%;
	background: #000;
	overflow: auto;
	margin: auto;
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
}

原理 :

通过 margin:auto 来实现上下左右的垂直居中。但是 margin:auto 有效,需要元素占据父元素所有的空间。所以设置 top,left,right,bottom 都设置为 0

缺点

  1. 缺点内部元素的宽高

5. translate

css
.box5 span {
	position: absolute;
	top: 50%;
	left: 50%;
	width: 100%;
	transform: translate(-50%, -50%);
	text-align: center;
}

优点 :

  1. 不定宽高。

缺点:

  1. 浏览器兼容性(适合移动端)

  2. 厂商前缀

  3. 可能与其他 transform 属性冲突

6. display:inline-block

css
.box7 {
	text-align: center;
	font-size: 0;
}

.box7 span {
	vertical-align: middle;
	display: inline-block;
	font-size: 16px;
}

.box7:after {
	content: '';
	width: 0;
	height: 100%;
	display: inline-block;
	vertical-align: middle;
}

7. display:flex 和 margin:auto

css
.box8 {
	display: flex;
	text-align: center;
}

.box8 span {
	margin: auto;
}