方法一:定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知寬高元素水平垂直居中</title>
</head>
<style>
.parent3{
position: relative;
height:300px;
width: 300px;
background: #FD0C70;
}
.parent3 .child{
position: absolute;
top: 50%;
left: 50%;
color: #fff;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent3">
<div class="child">hello world-3</div>
</div>
</body>
</html>
方法二:flex佈局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知寬高元素水平垂直居中</title>
</head>
<style>
.parent4{
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height:300px;
background: #FD0C70;
}
.parent4 .child{
color:#fff;
}
</style>
<body>div>