效果图如下:
浏览器放大缩小依旧不影响效果。
代码如下:
<!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>
.main_dom{
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
/* 1.第一种居中 定位 */
.div_parent1{
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
}
.div_son1{
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
border: 1px solid indigo;
}
/* 2.第二种居中 定位 */
.div_parent2{
margin-top: 50px;
position: relative;
width: 200px;
height: 200px;
border: 1px solid purple;
}
.div_son2{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
border: 1px solid chocolate;
}
/* 3.第三种居中 flex */
.div_parent3{
margin-top: 50px;
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
border: 1px solid yellow;
}
.div_son3{
width: 100px;
height: 100px;
border: 1px solid purple;
}
/* 4.第四种居中 特殊定位 */
.div_parent4{
margin-top: 50px;
position: relative;
width: 200px;
height: 200px;
border: 1px solid blueviolet;
}
.div_son4{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
border: 1px solid chocolate;
}
</style>
</head>
<body>
<div class="main_dom">
<!-- 1.第一种居中 定位-->
<div class="div_parent1">
<div class="div_son1"></div>
</div>
<!-- 2.第二种居中 定位-->
<div class="div_parent2">
<div class="div_son2"></div>
</div>
<!-- 3.第三种居中 flex -->
<div class="div_parent3">
<div class="div_son3"></div>
</div>
<!-- 4.第四种居中 -->
<div class="div_parent4">
<div class="div_son4"></div>
</div>
</div>
</body>
</html>