让盒子水平垂直居中是前端很基础的知识,在前端的面试中也经常会考查到,今天我就整理总结一下盒子水平垂直居中的几种方法。
盒子的设定
- 父盒子:width: 400px; height: 500px;
- 子盒子:width: 100px; height: 100px;
(当然也可以是其他数值,只是为了统一得到一个结果就提前给个设定)
预期结果
方法
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>定位完成盒子水平垂直居中</title>
<style>
.box{
position: relative;
width: 400px;
height: 500px;
background-color: skyblue;
}
.box1{
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
background-color: orange;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body&