方法一:利用flex弹性盒子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 600px;
height: 600px;
background: #dcdcdc;
display: flex;
justify-content: center;
align-items: center;
}
.box p{
width: 100px;
height: 100px;
background: #f00;
}
</style>
</head>
<body>
<div class="box">
<p></p>
</div>
</body>
</html>
方法二:利用定位position
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 600px;
height: 600px;
background: #dcdcdc;
position: relative;
}
.box p{
width: 100px;
height: 100px;
background: #f00;
position:absolute;
left: 0;
top: 0;
left: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box">
<p></p>
</div>
</body>
</html>
方法三:利用css3的transform属性:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{width: 600px;height: 600px;background: #dcdcdc;}
.box p{
width: 100px;
height: 100px;
background: #f00;
position: relative;
top: 50%;
transform: translateY(-50%);
margin:0 auto;
}
</style>
</head>
<body>
<div class="box">
<p></p>
</div>
</body>
</html>