<!DOCTYPE html>
<!--
盒子垂直居中对齐总结
注意: 方案3为弹性盒子,子元素会根据自身的宽度与高度来确定尺寸,
但是会自行伸长以吸收flex容器中额外的自由空间,也会缩短至自身最小尺寸以适应容器。
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
/* 方案1 */
#out1 {
position: relative;
width: 400px;
height: 400px;
background: blue;
}
#center1 {
position: absolute;
width: 200px;
height: 200px;
background: red;
margin: auto;
left: 0;
top: 0;
bottom: 0;
right: 0;
}
/* 方案2 */
#out2 {
position: relative;
width: 400px;
height: 400px;
background: blue;
}
#center2 {
position: absolute;
width: 200px;
height: 200px;
background: red;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
/* 方案3 */
#out3 {
display: flex;
width: 400px;
height: 400px;
background: blue;
}
#center3 {
margin: auto;
width: 100px;
height: 100px;
background: red;
}
</style>
</head>
<body>
<div id="out1">
<div id="center1">
</div>
</div>
<br />
<div id="out2">
<div id="center2">
</div>
</div>
<br />
<div id="out3">
<div id="center3">
</div>
</div>
</body>
</html>
至此。