一、什么是flex?
flex是css3中引入的一种布局方式,可以非常灵活高效控制元素的排列与对齐方式,大多数人称之为弹性布局.
二、怎么使用flex?
任何一个容器都可以指定为flex布局
#box {
display:flex;
}
三、flex的基本术语
- 采用flex布局的元素被称为flex容器 (flex container), 它的子元素即为flex元素 (flex item).
- flex容器中包含两个相互垂直的轴, 即主轴 (main axis)和副轴 (cross axis).
- flex元素沿主轴从主轴起点 (main start)到主轴终点 (main end)依次排布.
- 如果flex容器包含多行flex元素, 则flex行 (flex lines)沿副轴从副轴起点 (cross start)到副轴终点 (cross end)依次排布.
- 单个flex元素占据的主轴空间叫做主轴长度 (main size), 占据的副轴空间叫做副轴长度 (cross size).
四、有六个属性设置在父容器上,来控制子元素的显示方式:
属性 | 含义 |
---|---|
flex-direction |
主轴方向 |
flex-wrap |
换行样式 |
flex-flow |
前两个的简写形式 |
justify-content |
主轴对齐方式 |
align-items |
单行的副轴对齐方式 |
align-content |
多行的副轴对齐方式 |
五、flex-direction,设置主轴的对齐方向,有四个值:
-
row
(默认值):主轴为水平方向,起点在左端。 -
row-reverse
:主轴为水平方向,起点在右端。 -
column
:主轴为垂直方向,起点在上沿。 -
column-reverse
:主轴为垂直方向,起点在下沿。
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>flex布局 - by ghostwu</title>
<style>
#box {
display: flex;
flex-direction: row;
}
#box div {
width: 100px;
height: 100px;
background: #09f;
margin: 10px;
}
</style>
</head> <body>
<div id="box">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
</div>
</body> </html>
flex-direction设置为row:
flex-direction设置为row-reverse:
flex-direction设置为column,下面的示意图我只截取了前面5个div,后面如果截取的话,图片占的位置太多了,影响体验.
flex-direction设置为column-reverse:
六、flex-wrap :定义子元素超过一行,如何换行,常用属性值:
- nowrap(默认值):默认不换行。
- wrap:换行,第二行在第一行下面,从左到右
- wrap-reverse:换行,第二行在第一行上面,从左到右
#box {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
}
flex-wrap:nowrap;
flex-wrap: wrap;
flex-wrap: wrap-reverse;
七、flex-flow:是flex-direction 和flex-wrap的简写形式,默认是 row nowrap
#box {
display:flex;
/* flex-flow: row nowrap; */
/* flex-flow: row wrap; */
/* flex-flow: row wrap-reverse; */
/* flex-flow: row-reverse wrap-reverse; */
flex-flow: column wrap;
}
八、 justify-content: 子元素在主轴对齐方式
-
flex-start
(默认值):左对齐 -
flex-end
:右对齐 -
center
: 居中 -
space-between
:两端对齐,项目之间的间隔都相等。 -
space-around
:每个项目两侧的间隔相等。
#box {
display:flex;
flex-flow: row wrap;
/* justify-content: flex-start; */
/* justify-content: flex-end; */
/* justify-content: center; */
/* justify-content: space-between; */
justify-content: space-around;
}
这里主要搞清楚space-between和space-around的区别
justify-content: space-between;
justify-content: space-around;