<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
display: inline-block;
}
.a{
width:500px;
height:600px;
border:1px solid gray;
}
.b{
width:70px;
height:70px;
border:1px solid red;
position: relative;
top:50%; //注意:以div#b的上边框为基准的50%
margin-top:-35px;
/*transform: translateY(-50%)*//div向上平移(translate)自身高度的一半(50%),在不确定自身高度的情况下用这种比较好
}
</style>
</head>
<body>
<div class='a'>
<div class='b'></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{
display: inline-block;
}
.a{
width:500px;
height:600px;
border:1px solid gray;
display: flex;
/*justify-content: center;*//使子元素 水平居中
align-items: center;//使子元素 垂直居中
}
.b{
width:70px;
height:70px;
border:1px solid red;
}
</style>
</head>
<body>
<div class='a'>
<div class='b'></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.a{
width:500px;
height:600px;
border:1px solid gray;
display: table-cell;//需要子元素垂直居中的设置table-cell及vertical-align
vertical-align: middle;
}
.b{
width:70px;
height:70px;
}
</style>
</head>
<body>
<div class='a'>
<div class='b'>要居中的内容</div>
</div>
</body>
</html>