div盒子水平居中垂直居中的几种方法:
一、子盒子固定宽高时:
法一:使用margin: auto;
{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 800px;height: 400px;background: #ccc;position:relative;
}
.box {
width: 400px;height: 200px;background-color: #47c730;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
法二:使用 负margin
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 800px;height: 400px;background: #ccc;position:relative;
}
.box {
width: 400px;height: 200px;background-color: #47c730;
position: absolute;
top: 50%;
left: 50%;
margin-left: -200px;
margin-top: -100px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
二、盒子宽高不固定
法一、使用flex布局,给父元素添加display: flex; justify-content: center;align-items: center;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 800px;height: 400px;background: #ccc;
display: flex;
justify-content: center;
align-items: center;
}
.box {
background-color: #47c730;
}
</style>
</head>
<body>
<div class="container">
<div class="box">我没宽度和高度</div>
</div>
</body>
</html>
法二、使用position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 800px;height: 400px;background: #ccc;
position: relative;
}
.box {
background-color: #47c730;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="container">
<div class="box">我没宽度和高度</div>
</div>
</body>
</html>