div居中上下对齐(div叠加在上方居中对齐)

方法一

#wrap{ position:absolute; width:300px; height:200px; top:50%; left:50%; transform:translate(-50%,-50%) ; background:#009688; } 若是下面的代码,其结果就是错误的

#wrap{
 width:300px;
 height:200px;
 margin-top:50%;
 margin-left:50%;
 transform:translate(-50%,-50%) ;
 background:#009688;
 }

原因:

当margin设置成百分数的时候,其top right bottom left的值是参照父元素盒子的宽度进行计算

方法二

直接用弹性盒布局,作用于父元素上实现

parent{
 width:100%;
 height:100vh;
 display:flex;
 justify-content: center;//子元素水平居中
 align-items: center;//子元素垂直居中
赞(0)