1.传统意义,position定位
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题</title>
<style>
.box{
width: 300px;
height: 300px;
background: #333;
position: absolute;
top:50%;/*这里的50%是box的父级的高度的50%*/
left:50%;/*这里的50%是box的父级的宽度的50%*/
margin-top: -150px;
margin-left: -150px;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
2.利用display:flex,给div的父级设置相关样式
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题</title>
</head>
<style>
body{
display: flex;
align-items: center;
justify-content: center;
}
div{
width: 300px;
height: 300px;
background: #333;
}
</style>
<body>
<div></div>
</body>
</html>
注意:使用flex的时候,有兼容性问题