盒子居中的四种方法
第一种方法
利用定位position: absolute和position: relative子绝父相, 子盒子移动父子高度和宽度的一半,再用外边距让子盒子移动自身高度和宽度的一半,代码如下
<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: cadetblue;
margin: 100px auto;
}
.son {
/* 子盒子添加绝对定位 */
position: absolute;
/* 分别向下向左走父盒子的一半 */
top: 50%;
left: 50%;
/* 外边距让子盒子分别向下向左走子盒子自身高度宽度的一半 */
margin-top: -100px;
margin-left: -100px;
width: 200px;
height: 200px;
background-color: brown;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
第二种方法
先利用定位position: absolute和position: relative子绝父相, 子盒子移动父子高度和宽度的一半,再用变换属性(transform)里的位移(translate)属性值移动自身高度宽度的一半,代码如下
<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: cadetblue;
margin: 100px auto;
}
.son {
/* 子盒子添加绝对定位 */
position: absolute;
/* 分别向下向左走父盒子的一半 */
top: 50%;
left: 50%;
/* 利用变换属性的位移属性值移动子盒子自身高度宽度的一半 */
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: brown;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
第三种方法
同样是先定位子绝父相 (方法同上) ,然后将子盒子的top,left,right,bottom四个值全部设为0,最后将margin值为auto(:auto会自动去计算子元素和父元素之间的边距,并设为居中),代码如下
<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: cadetblue;
margin: 100px auto;
}
.son {
/* 子盒子添加绝对定位 */
position: absolute;
/* 四边设置为0 */
top: 0;
left: 0;
right: 0;
bottom: 0;
/* 设置margin居中 */
margin: auto;
width: 200px;
height: 200px;
background-color: brown;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
第四种方法
利用flex弹性布局,将父盒自设置为display: flex;然后给父盒子分别添加justify-content: center(垂直居中) align-items: center(水平居中) flex布局的属性都是给父盒子设置,代码如下
<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;
width: 400px;
height: 400px;
background-color: cadetblue;
margin: 100px auto;
/* 垂直居中 */
justify-content: center;
/* 水平居中 */
align-items: center;
}
.son {
width: 200px;
height: 200px;
background-color: brown;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
四种效果均如下图