第一种方法:
position:fixed;
left:50%;top:50%;
margin-left:-元素宽度一半;
margin-top:-元素高度的一半;
第二种方法:(常用)
position:fixed;
left:0;right:0;
top:0;bottom:0;
margin:auto;
第三种方法:利用transform居中
width: 100px;
height: 100px;
background-color: red;
position: absolute; 开启子绝父相
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
<!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>
body{
height: 2000px;
}
div{
/* font-size : 5vh; */
width: 200px;
height: 200px;
background-color: red;
/* 固定定位和绝对定位脱离文档流
相对定位和粘滞定位不会脱离文档流
*/
/* 第一种
position: fixed;
top:50%;
left:50%;
margin-left: -100px;
margin-top: -100px; */
/* 第二种
position: fixed;
left:0;
top:0;
right:0;
bottom:0;
margin: auto; */
/* 粘滞定位
position:sticky;
top:100px; */
}
</style>
</head>
<body>
<div></div>
</body>
</html>