方法一:利用定位(常用方法,推荐)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #000;
position: relative;
}
.child {
-------------
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
------------------------
width: 100px;
height: 100px;
border: 1px solid #999;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">我是子元素</div>
</div>
</body>
</html>
方法二:利用 margin:auto;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.parent {