<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.wrap{
width: 600px;
height: 800px;
background: gray;
position: relative;
margin: 300px auto;
}
.box{
width: 300px;
height: 400px;
background: #000;
position: absolute;
top: 50%;
margin-top: -50%;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box"></div>
</div>
</body>
</html>
效果和没设置margin-top top前一样,不同之处在于现在的.box脱离了父级
如果我们尝试下修改父级.wrap的宽度为800px,会发现以下情况:
黑色块往上移动了100px 刚好等于800/2-300,由此可知,margin-top是相对position:releative;父级的宽度而言的,