首先把基础的html和css写出来:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="flex-contain">
<div class="flex">item1</div>
<div class="flex">item2</div>
<div class="flex">item3</div
</div>
</body>
</html>
.flex{
width: 100px;
height: 100px;
background: blue;
margin: 10px;
color: white;
}
此时效果是这样的:
当我们将给这三个box的容器加上flex元素之后,所有元素有了水平主轴:
.flex-contain{ //添加box的容器
display: flex;
}
.flex{
width: 100px;
height: 100px;
background: blue;
margin: 10px;
color: white;
}
为了看清楚添加黄色背景,
使用justify-content设置水平居中
.flex-contain{
display: flex;
background: yellow;
justify-content: center;
}
使用align-items设置垂直居中:
.flex-contain{
height: 300px;
display: flex;
background: yellow;
justify-content: center;
align-items: center;
}