1、flex
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>居中方式</title>
<style>
.box {
display: flex;
justify-content: center;
align-items: center;
}
.box>div {
width: 100px;
height: 100px;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>
2、position
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>居中方式</title>
<style>
.box {
position: relative;
}
.box>div {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>
3、position+transform
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>居中方式</title>
<style>
.box {
position: relative;
}
.box>div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="box">
<div></div>
</div>
</body>
</html>
4、table-cell
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>居中方式</title>
<style>
.box {
display: table;
height: 800px;
width: 800px;
border: 1px solid red;
}
.son {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.inside {
background-color: #000;
display: inline-block;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="box">
<div class="son">
<div class="inside"></div>
</div>
</div>
</body>
</html>