搞定CSS面试必问:盒子如何实现水平垂直居中?
最编程
2024-01-26 07:07:04
...
介绍
开发中经常遇到盒子垂直水平居中的问题,一个未知宽度的盒子在水平和垂直方向上都居中,本文汇总了三种简单常用的盒子居中方法。
初始结构
<!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>
<style>
.father {
width: 400px;
height: 400px;
background-color: red;
}
.son {
width: 200px;
height: 200px;
background-color: #bfa;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
如图所示
接下来,给son实现盒子垂直水平居中
方法一:定位+margin
<!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>
<style>
.father {
position: relative;
width: 400px;
height: 400px;
background-color: red;
}
.son {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 200px;
background-color: #bfa;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
方法二:定位+位移
<!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>
<style>
.father {
position: relative;
width: 400px;
height: 400px;
background-color: red;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: #bfa;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
方法三:flex布局
<!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>
<style>
.father {
display: flex;
align-items: center;
justify-content: center;
width: 400px;
height: 400px;
background-color: red;
}
.son {
width: 200px;
height: 200px;
background-color: #bfa;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
以上三种方法就能实现一个未知盒子宽高的情况下让其水平居中
下一篇: 搞定垂直居中!CSS盒子的几种常用技巧