第一种:绝对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"> <style>
.box {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
第二种:flex布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.flex {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class="flex">
<div class="box"></div>
</div>
</body>
</html>
第三种:grid布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.flex {
width: 100%;
height: 100vh;
display: grid;
place-items: center;
}
.box {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class="flex">
<div class="box"></div>
</div>
</body>
</html>