居中 div


行內水平居中

.container {
	text-align: center;
}

區塊水平居中

.center {
	width: 200px;
  margin: 0 auto;
}

多個區塊水平居中

.container {
	text-align: center;
  > .center {
		display: inline-block;
	}
}

or 

.container {
	display: flex;
  justify-content: center;
}

絕對定位 ( 已知寬高 )

.container {
	position: relative;
	> .center {
		position: absolute;
	  width: 300px;
	  height: 300px;
	  margin: auto;
	  top: 0;
	  left: 0;
	  bottom: 0;
	  right: 0;
	}
}

任意元素 ( 未知寬高 )

.container {
	position: relative;
  > .center {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}
}

or 

.container {
	display: flex;
	align-items: center;
	justify-content: center;
	> .center {
		width: 100px;
	  height: 100px;
	}
}

Flexbox 適用場景


高效的方式對容器中的項目佈局、對齊和分配空間