创建一个flex容器
创建方式:
display:flex
代码展示:
html
<div class="body">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
css
.body {
display: flex;
background-color: pink;
}
.body .flex-item:first-child {
background-color: yellow;
}
.body .flex-item:nth-child(2) {
background-color: cornflowerblue;
}
.body .flex-item:last-child {
background-color: red;
}
效果:
创建一个容器,将其设置为flex布局,那么默认情况下,该容器内所有的子容器都是flex布局,并且排序方式为从左到右依次排序在一行中。
flex-direction属性
控制容器内元素的排序方向(主轴),具体有四个值, 分别为:
flex-direction:row // 从左往右 排序在一行
flex-direction:row-reverse // 从右往左 排序在一行
flex-direction:column // 从上往下 排序在一列
flex-direction:column-reverse // 从下往上 排序在一列
四种展示效果:
flex-direction:row
flex-direction:row-reverse
flex-direction:column
flex-direction:column-reverse
justify-content属性
控制flex容器内的子元素排序方向(主轴)上的对齐方式。例如:如果排序方向为row,那么默认的展示方式为靠游览器最左侧在一行内排序,这个属性可以设置为靠右侧排序。
有六个值,分别为:
justify-content:center // 居中对齐
justify-content:flex-start // 靠容器的开头对齐,默认对齐方式。
justify-content:flex-end // 靠容器的末尾对齐
justify-content:space-around // 元素之前、之后有空格的填充排序
justify-content:space-between // 元素之间有空格的填充排序
justify-content:space-evenly // 元素之前、之后有空格,并且相邻元素之间空格不堆叠
六种展示效果:
justify-content:center
justify-content:flex-start
jsutify-content:flex-end
justify-content:space-around
justify-content:spact-between
justify-content:space-evently
网上的一张图很清楚的解释了这六种值的表现形式:
align-items属性
垂直于排序方向的上的对齐方式。垂直于排序方向(主轴):交叉轴。
例如:flex容器内如果一个元素在主轴上是靠左上角展示,如果想让它在垂直方向上靠下排序,即展示在左下角,那么可以使用这个属性。
它有五个值:
align-items:center // 交叉轴上在中间显示
align-items:flex-start // 交叉轴上在上面显示
align-items:flex-end // 交叉轴上在下面显示
align-items:stretch // 交叉轴上拉伸填充满容器(默认)
align-itesm:baseline // 基线对齐
align-self属性
align-items属性为定义在flex容器上,使内部的元素按照指定的规则进行展示。而当我们想自定义某个元素的展示方式的时候,就可以使用align-self属性。
它的属性值和align-items应该是一致的,这里展示一个效果演示。
html
<div class="body">
<div class="flex-item">1</div>
<div class="flex-item">2 <br> 2 <br> 2</div>
<div class="flex-item">3 <br> 3 <br> 3 <br> 3 <br> 3</div>
</div>
css
.body {
display: flex;
justify-content:center;
align-items: center;
background-color: pink;
}
.body .flex-item {
padding: 20px;
}
.body .flex-item:first-child {
background-color: yellow;
align-self: flex-end;
}
.body .flex-item:nth-child(2) {
background-color: cornflowerblue;
}
.body .flex-item:last-child {
background-color: red;
}
展示效果