第一种方法:flex
<style>
.wrap{
width: 400px;
height: 400px;
background:rgba(0,0,0,.2);
display: flex;
justify-content:center;
align-items:center;
}
.box{
width: 200px;
height: 200px;
background:rgba(0,0,0,.5);
}
</style>
</head>
<body>
<div class="wrap">
<div class="box"></div>
</div>
</body>
第二种:position,margin
<style>
.wrap{
width: 400px;
height: 400px;
background:rgba(0,0,0,.2);
position: relative;
}
.box{
width: 200px;
height: 200px;
background:rgba(0,0,0,.5);
position:absolute;
left:0;
top:0;
right:0;
bottom:0;
margin:auto;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box"></div>
</div>
</body>
第三种:position,transform
<style>
.wrap{
width: 400px;
height: 400px;
background:rgba(0,0,0,.2);
position: relative;
}
.box{
width: 200px;
height: 200px;
background:rgba(0,0,0,.5);
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="wrap">
<div class="box"></div>
</div>
</body>
第四种:table-cell
<style>
.wrap{
width: 400px;
height: 400px;
background:rgba(0,0,0,.2);
text-align: center;
display: table-cell;
vertical-align: middle;
}
.box{
width: 200px;
height: 200px;
background:rgba(0,0,0,.5);
display:inline-block;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box"></div>
</div>
</body>