明确宽与高
父元素relative+子元素absolute+top/bottom/right/left:0
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.out{
width:300px;
height:200px;
background-color: orange;
position: relative;
}
.in{
width:100px;
height:100px;
background-color: blue;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="out">
<div class="in"></div>
</div>
</body>
父元素relative+子元素absolute+top/left:50%+margin-top/left=-一半宽度
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.out{
width:300px;
height:200px;
background-color: orange;
position: relative;
}
.in{
width:100px;
height:100px;
background-color: blue;
position: absolute;
top:50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="out">
<div class="in"></div>
</div>
</body>
不明确宽与高
父元素relative+子元素absolute+top/left:50%+translateX(-50%)translateY(-50%)
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.out{
width:300px;
height:200px;
background-color: orange;
position: relative;
}
.in{
width:100px;
height:100px;
background-color: blue;
position: absolute;
top:50%;
left: 50%;
transform: translateX(-50%)translateY(-50%);
}
</style>
</head>
<body>
<div class="out">
<div class="in"></div>
</div>
</body>
flex定位 justify-content:center+align-items:center
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.out{
width:300px;
height:200px;
background-color: orange;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.in{
width:100px;
height:100px;
background-color: blue;
position: absolute;
}
</style>
</head>
<body>
<div class="out">
<div class="in"></div>
</div>
</body>