SOURCE

console 命令行工具 X clear

                    
>
console
<h2>水平居中</h2>
<div>子元素display:block,宽度固定,margin:0 auto</div>
<div class="box1">
	<div class="item1"></div>
</div>

<div>子元素display:inline-block/inline,text-align:center</div>
<div class="box2">
	<div class="item2"></div>
</div>

<div>子元素宽度固定,margin-left负值</div>
<div class="box3">
	<div class="item3"></div>
</div>

<div>子元素宽度不固定,transform</div>
<div class="box4">
	<div class="item4"></div>
</div>

<h2>水平垂直居中</h2>
<div>position:absolute,margin:auto</div>
<div class="box5">
	<div class="item5"></div>
</div>
.box1 {
	padding: 0;
	margin: 0;
	width: 200px;
	height: 200px;
	background: black;
}

.item1 {
	margin: 0 auto;
	width: 50px;
	height: 50px;
	background: red;
}
.box2 {
	padding: 0;
	margin: 0;
	width: 200px;
	height: 200px;
	text-align: center;
	background: black;
}

.item2 {
	display: inline-block;
	width: 50px;
	height: 50px;
	background: red;
}

.box3 {
	position: relative;
	padding: 0;
	margin: 0;
	width: 200px;
	height: 200px;
	background: black;
}

.item3 {
	position: absolute;
	left: 50%;
	margin-left: -25px;
	width: 50px;
	height: 50px;
	background: red;
}

.box4 {
	position: relative;
	padding: 0;
	margin: 0;
	width: 200px;
	height: 200px;
	background: black;
}

.item4 {
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
	width: 50px;
	height: 50px;
	background: red;
}

.box5 {
	position: relative;
	padding: 0;
	margin: 0;
	width: 200px;
	height: 200px;
	background: black;
}

.item5 {
	position: absolute;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	margin: auto;
	width: 50px;
	height: 50px;
	background: red;
}