布局如下
<html>
<head>
<meta charset="utf-8">
<title>测试</title>
</head>
<body>
<div id="parent" style="width: 300px;height: 300px;border: 1px solid #0000FF;">
<div id="child" style="width: 100px;height: 100px;border: 1px solid #FF0000;"></div>
</div>
</body>
</html>
绝对定位
#parent {
position: relative;
}
#child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
transform
#child {
margin: 0 auto;
position: relative;
top: 50%;
transform: translateY(-50%); /* 元素往下位移自身高度50%的距离 */
}
弹性布局(flex)
#parent {
display: flex;/*设置为弹性容器,默认主轴为横轴*/
align-items: center;/*交叉轴上如何对齐*/
justify-content: center;/*在主轴上的对齐方式,这里为居中*/
}