设置了display:flex之后,子元素会自动的变为弹性盒子的子元素,
被称为flex items
③ 默认情况,所有的 flex-item 会按照 flex 容器的顶部和左侧对齐。
实例2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#item-container {
display: flex;/*启用flex布局*/
background-color: pink;
justify-content:flex-start;/*默认*/
justify-content:flex-end;/*在主轴的末端对其*/
justify-content:center;/*在主轴的中间对其*/
justify-content:space-between;/*在整个主轴中平均分配空间,无论其中有多少个元素*/
justify-content:space-around;/*Flex-item 默认会被均匀的分布,但是每一个
都会在其给定的空间内居中显示。*/
align-items:center;/*让items在垂直方向上居中*/
}
.square {
width: 200px;
height: 200px;
background-color: orange;
}
.circle {
border-radius: 50%;
width: 150px;
height: 150px;
background-color: green;
}
</style>
</head>
<body>
<div id="item-container">
<div class="circle"></div>
<div class="square"></div>
<div class="circle"></div>
</div>
</body>
</html>
代码效果如下:
我们可以通过非常简单的属性设置来调整对其方式,例如:
justify-content: flex-start / flex-end /center /space-between /space-around
我们也可以通过align-items:center 属性让 items 在垂直方向居中。
实例3:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#item-container {
display: flex;/*启用flex布局*/
background-color: pink;
justify-content:flex-start;/*默认*/
justify-content:flex-end;/*在主轴的末端对其*/
justify-content:center;/*在主轴的中间对其*/
justify-content:space-between;/*在整个主轴中平均分配空间,无论其中有多少个元素*/
justify-content:space-around;/*Flex-item 默认会被均匀的分布,但是每一个
都会在其给定的空间内居中显示。*/
align-items:center;/*让items在垂直方向上居中*/
}
.square {
width: 200px;
height: 200px;
background-color: orange;
order: -1; /*让正方形显示在第一位而不是中间*/
}
.circle {
border-radius: 50%;
width: 150px;
height: 150px;
background-color: green;
}
</style>
</head>
<body>
<div id="item-container">
<div class="circle"></div>
<div class="square"></div>
<div class="circle"></div>
</div>
</body>
</html>
实例3 和 实例2 大体相似,但是在.square类里存在一句order:-1,可以更改元素的渲染顺序。这个是弹性盒模型中一个非常厉害的一个方面。
实例3代码效果如下:
flex布局方式属性
在flex整个体系当中,大体上可以分为两类,一类是给父容器设置的属性,一类是给父容器中子元素设置的属性。
弹性容器属性 -- 给父元素设置的属性
1.flex-direction 定义内部元素如何在flex容器中布局,定义了主轴的方向(是正是反)。
语法:
row | row-reverse | column | column-reverse
row 默认值,子元素会排列在一行 从主轴左侧开始
row-reverse 子元素会排列在一行。不过是从右侧开始
column 子元素垂直显示,从侧轴起始点开始
column-reverse 垂直显示,不过从结束点开始
实例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 100%;
height: 500px;
border:1px solid #ccc;
display:flex;
flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;
}
.container div {
width: 100px;
height: 100px;
background-color: orange;
}
</style>
</head>
<body>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<