共7种方法
<!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>
*{
margin: 0;
padding: 0;
}
/* 法1:父设置宽高,并且text-align:center;line-height:父高度;
子设置宽高,并且vertical-align:middle;display:inline-block
*/
/* .outer{
width: 100vw;
height: 100vh;
background-color: green;
text-align: center;
line-height: 100vh;
}
.inner{
width: 100px;
height: 100px;
background-color: red;
display: inline-block;
vertical-align: middle;
} */
/* 法2:父设置宽高,并且display:table-cell;text-align:center;vertical-align:middle
子设置宽高,并且display:inline-block;
*/
/* .outer{
width: 100vw;
height: 100vh;
background-color: green;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.inner{
width: 100px;
height: 100px;
background-color: red;
display: inline-block;
} */
/* 法3:父设置宽高,并且position:relative
子设置宽高,并且position:absolute;top:50%;left:50%;transform: translate(-50%,-50%);
*/
/* .outer{
width: 100vw;
height: 100vh;
background-color: green;
position: relative;
}
.inner{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
} */
/* 法4:父设置宽高,并且display:flex;justify-content:center;align-items:center */
/* .outer{
width: 100vw;
height: 100vh;
background-color: green;
display: flex;
justify-content: center;
align-items: center;
}
.inner{
width: 100px;
height: 100px;
background-color: red;
} */
/* 法5:使用calc基于当前页面布局进行设计 */
/* .outer{
width: 100vw;
height: 100vh;
background-color: green;
position: relative;
}
.inner{
width: 100px;
height: 100px;
position: absolute;
background-color: red;
left: calc(50% - 50px);
top: calc(50% - 50px);
} */
/* 法6:父设置宽高,relative
子设置宽高,absolute,top,left,复margin
*/
/* .outer{
width: 100vw;
height: 100vh;
background-color: green;
position: relative;
}
.inner{
width: 100px;
height: 100px;
position: absolute;
background-color: red;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
} */
/* 法7:父设置:position:relative
子设置top,right,bottom,left都是0,margin:auto */
.outer{
width: 100vw;
height: 100vh;
background-color: green;
position: relative;
}
.inner{
width: 100px;
height: 100px;
position: absolute;
background-color: red;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner">
</div>
</div>
</body>
</html>