通过flex实现
代码
<div style="background-color: blue;width: 100%;height: 500px;display: flex;align-items: center;justify-content: center;">
<div style="background-color: red;width: 200px;height: 200px;"></div>
</div>
备注
- align-items:center 实现垂直居中
- justify-content:center 实现水平居中
实现效果
margin和positiion定位实现
代码
<div style="background-color: yellow;width: 100%;height: 500px;">
<div style="background-color: red;width: 200px;height: 200px;margin: 0 auto;position: relative;top:50%;transform:translateY(-50%)"></div>
</div>
备注
margin:0,auto 实现水平居中
position:relative 改变默认的static 是指处于文档流中
top:50% 让子元素在父元素的中间,但是是从子元素顶部算起的
transform:translateY(-50%) 让它从子元素y轴中心算起