position relative top失效的问题,温习下常用两种的居中方式

时间:2023-03-09 06:50:23
position relative top失效的问题,温习下常用两种的居中方式
因为body和html,默认高度是auto

所以相对于他们作为父元素设置position:relative的top值需要加上body,html{height:100%;}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<style type="text/css">
  *{margin: 0; padding: 0;list-style: none;}
   html,body{height:100%;} /* 相对屏幕必填写 */
    /*.maxbox{width: 500px;height: 500px;background-color:pink;position:relative;top:50%;left:50%;transform:translate(-50%,-50%);} 选其一*/
    .maxbox{width: 500px;height: 500px;background-color:pink;position:relative;top:50%;left:50%;margin:-250px 0 0 -250px;}
    .maxbox div{width: 200px;height: 200px;background-color:red;position:absolute;top:50%;margin-top:-100px;left:0;}
</style>
<body>
<div class="maxbox">
<div></div>
</div>
</body>
</html>