方法一 :
利用transform属性中的(平移)translate(x,y)和绝对定位 来进行元素居中
<!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>
.box{
width: 300px;
height: 300px;
background-color: red;
transition: all 1s;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-150px,-150px);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
方法二 :
用margin:auto和绝对定位来进行元素居中
<!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>
.box{
width: 300px;
height: 300px;
background-color: red;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
方法三:
直接利用绝对定位来进行元素居中
<!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>
.box{
width: 300px;
height: 300px;
background-color: #f00;
border-radius: 30px;
margin: 0 auto;
position: absolute;
top:calc(50% - 150px);
left: calc(50% - 150px);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>