前言
网页中定div水平垂直居中的方法
一、准备部分
<!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>
</head>
<style>
* {
margin: 0px;
height: 0px;
}
.box {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box"></div>
</body>
</html>
二、水平垂直居中的方法
1.方法一
<!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>
</head>
<style>
* {
margin: 0px;
height: 0px;
}
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
<body>
<div class="box"></div>
</body>
</html>
2.方法二
<!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>
</head>
<style>
* {
margin: 0px;
height: 0px;
}
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
<body>
<div class="box"></div>
</body>
</html>
3.方法三
<!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>
</head>
<style>
* {
margin: 0px;
height: 0px;
}
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="box"></div>
</body>
</html>
。