有7中方法可以实现这个要求
1、先回答最长用的方式定位
整体方案 父相自绝
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.parent {
width: 500px;
height: 500px;
background-color: skyblue;
position: relative;
}
.child {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
}
</style>
</head>
<body>
<div class='parent'>
<div class='child'></div>
</div>
</body>
</html>
第一种 transform
给子元素添加
.child {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
第二种 margin
给子元素添加
.child {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom:0;
margin: auto;
}
第三种 margin
给子元素添加
.child {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
第四种
给子元素添加
.child {
width: 200px;
height: 200px;
background-color: pink;
position: absolute;
margin-left: 150px;
margin-top: 150px;
}
第五种 也是最常用的 flex
flex布局
.parent {
width: 500px;
height: 500px;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 200px;
height: 200px;
background-color: pink;
}
第六种 table-cell
table-cell布局
.parent {
width: 500px;
height: 500px;
background-color: skyblue;
display: table-cell;
vertical-align: middle;
}
.child {
width: 200px;
height: 200px;
background-color: pink;
margin: 0 auto;
}
第七种 这就是错误的不能搞
转换成行内块元素
.parent {
width: 500px;
height: 500px;
background-color: skyblue;
text-align: center;
line-height: 700px;
}
.child {
width: 200px;
height: 200px;
background-color: pink;
display: inline-block;
}
第八种
<body>
<div class='parent' id='parent'>
<div class='child' id='child'></div>
</div>
<script>
let parent = document.getElementById('parent');
let child = document.getElementById('child');
let parentW = parent.offsetWidth;
let parentH = parent.offsetHeight;
let childW = child.offsetWidth;
let childH = child.offsetHeight;
parent.style.position = "relative"
child.style.position = "absolute";
child.style.left = (parentW - childW) / 2 + 'px';
child.style.top = (parentH - childH) / 2 + 'px';
</script>
</body>