一.通过flex让盒子水平垂直居中
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>Document</title>
</head>
<body>
<div class="header">
<div class="box1">1</div>
</div>
</body>
<style>
.header {
width: 300px;
height: 300px;
border: 1px solid #c22;
margin: 100px auto;
}
.box1 {
width: 50px;
height: 50px;
background-color: pink;
}
</style>
</html>
box1在header里面进行水平和垂直居中。
2.图示
3.flex布局
1.给父盒子开启弹性布局
display: flex;
2.水平居中
justify-content: center;
3.换个主轴 |默认情况下是row
flex-direction: column;
4.垂直居中
align-items: center;
图示:
4.通过定位的方式
hader盒子
position: relative;
box1盒子
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
图示:
二.在父盒子里面开启弹性布局会触发BFC模式
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>Document</title>
</head>
<body>
<div class="header">
<div class="box1">1</div>
<div class="box2">2</div>
<div class="box3">3</div>
</div>
</body>
<style>
.header {
width: 300px;
height: 300px;
border: 1px solid #c22;
margin: 100px auto;
/* display: flex;
justify-content: center;
flex-direction: column;
align-items: center; */
/* display: flex; */
}
.box1 {
width: 50px;
height: 50px;
background-color: pink;
}
.box2 {
width: 50px;
height: 50px;
background-color: aqua;
}
.box3 {
width: 50px;
height: 50px;
background-color: aquamarine;
}
</style>
</html>
2.图示
3.开启弹性布局后
display: flex
二.justify-content的几个应用
1.水平居中( justify-content: center)。
2. justify-content: space-around
3.justify-content: space-between
4.justify-content: space-evenly(所有的均匀分配)
5.让盒子和文字水平居中对齐
<!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>
</head>
<body>
<div class="main">
<div class="header">
<div class="box1">1</div>
<span>我是一段文字</span>
</div>
</div>
<style>
.main {
width: 300px;
height: 300px;
background-color: pink;
margin: 100px auto;
}
.header {
background-color: aqua;
display: flex;
justify-content: space-between;
align-items: center;
}
.box1 {
width: 50px;
height: 50px;
background-color: brown;
}
</style>
</body>
</html>
解析:开启弹性布局后, justify-content: space-between;两边进行对齐,align-items: center;水平进行居中。
图示: