首先什么是flex布局呢,flex是flexible box的缩写,意思是弹性布局。用来为盒状模型提供最大的灵活性。
任何容器都可以指定为flex布局。
块级元素,行内元素,行内块元素类型的元素都可以设为flex布局。
下面举例
div.container{
display:flex;
}
flex布局分为两块,一是最外层的flex容器,也就是我们设置为display:flex的容器。这个容器的直接子元素就会变成flex项。
关于flex布局知识点我觉得也是分成两块,一是关于flex容器的相关属性,二事关于flex项目的属性。现在我们先来说一下flex容器相关的属性
1:flex-direction
这个属性主要是决定flex项的排列方向,是纵向排列还是横向排列,有以下四个值可选
flex-direction:row | row-reverse | column | column-reverse
这是我的页面结构,这里我这是flex-direction:row,我们看到flex项也就是container的子元素是一行排列。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.container{
display: flex;
background: red;
width: 300px;
flex-direction: row;
}
.box{
padding:20px;
background-color: #B1FF84;
}
.box:first-child{
background-color: #0099ff;
}
.box:last-child{
background-color:#FF6D10
}
</style>
</head>
<body>
<div class="container">
<div class="box">11</div>
<div class="box">22</div>
<div class="box">33</div>
</div>
</body>
</html>
flex-direction:row-reverse,这样跟设置成row的区别在于也是一行排列,但是是从右边开始排列第一个子元素,看图
flex-direction:column,我们看到flex项也就是container的子元素是竖着排列。
flex-direction:column-reverse,这样也是竖着排列,只是第一个子元素从底部开始排列。效果图如下
2:flex-wrap属性
该属性可取值为:nowarp | warp | warp-reverse
flex-wrap:nowrap,代表不换行,即使子元素的宽度总和超过了父元素的宽度,也不会换行(这里子元素的宽度总和超过了父元素)。效果图如下
flex-wrap:wrap;这样会在需要换行的地方换行
flex-wrap:wrap-reverse,也会在需要换行的地方进行换行,但是换行的时候会在上面生成第二行
3:flex-flow属性
这是上面两个属性的综合简写模式,默认值是row和nowarp
4:justify-content属性
该属性可取值有
justify-content: flex-start | flex-end | center | space-between | space-around;
justify-content: flex-start:从左边开始排列
justify-content: flex-end;子元素靠右排列
justify-content: center:子元素居中排列
justify-content: space-between:两端对齐,子元素从左到右均匀排列
justify-content:space-around:每个子元素左右两边间隙相等的分布在flex盒模型中,因为每个子元素左右两边都有相同的间隙,所以相邻的两个子元素之间的间隙是单个子元素间隙的两倍大
5:align-items属性
align-items: flex-start | flex-end | center | baseline | stretch;
align-items:flex-start,flex项跟flex盒子上面对齐
align-items:flex-end,flex项跟flex盒子下面对齐
align-items:center,flex项跟flex盒子上下居中对齐
align-items:baseline,flex项里的文字下面的基线对齐
- stretch(默认值):如果项目未设置高度或设为auto,将占满整个容器的高度。
6:align-content属性
可取值有: align-content: flex-start | flex-end | center | space-between | space-around | stretch;
这是针对多行子元素的时候
align-content: flex-start
align-content: flex-end
align-content: center
- flex-start:与交叉轴的起点对齐。
- flex-end:与交叉轴的终点对齐。
- center:与交叉轴的中点对齐。
- space-between:与交叉轴两端对齐,轴线之间的间隔平均分布。
- space-around:每根轴线两侧的间隔都相等。所以,轴线之间的间隔比轴线与边框的间隔大一倍。
- stretch(默认值):轴线占满整个交叉轴。