flex布局背景
在2009
年,W3C
提出了flex
布局,它可以很简单、方便的实现各种布局。目前,所有的浏览器都可以支持。
如何使用flex布局
如果使用
flex
布局,子元素的float
、clear
、vertical-align
属性都将失效
// css
.box {
display: flex; // 块级元素
display: inline-flex; // 行内元素
display: -webkit-flex; // webkit内核浏览器
}
flex布局属性
我们从两个方向出发解释flex如何布局,一为主轴(即为横轴)方向,二为交叉轴(即为纵轴)方向。
- 属性flex-direction的值
- row: 主轴方向(从左至右)[默认值]
- row-reverse: 主轴方向(从右至左)
- column: 交叉轴方向(从上至下)
- column-reverse: 交叉轴方向(从下至上)
- 横轴方向
- 如果想要在主轴方向对齐,那么首先要控制其
flex-direction
值为row
,代码为
.box {
display: flex;
flex-direction: row;
}
- 然后我们来研究在主轴上对齐的属性
justify-content:控制主轴上所有元素对齐
// 属性值
.box {
justify-content: flex-start; // 向左对齐 [默认值]
justify-content: flex-end; // 从右对齐
justify-content: center; // 居中对齐
justify-content: space-between; // 两端对齐
justify-content: space-around; // 均匀排列,每个元素周围分配相同的空间
}
3.实例
- flex布局对元素的影响
// html
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
<div class="box3">box3</div>
</div>
// css
.box {
width: 400px;
height: 200px;
border: 1px solid #000;
/*探究flex布局对元素的影响*/
/*display: flex;
flex-direction: row;*/
}
.box div {
width: 100px;
}
.box1 {
border: 1px solid red;
}
.box2 {
border: 1px solid blue;
}
.box3 {
border: 1px solid green;
}
- 如果我们只给父元素设置
height
,而不设置子元素的height
,在不使用flex
布局时,子元素的height
由子元素中的内容撑开,而当使用flex
布局时,子元素的height
由父元素决定,子元素会充满整个父元素
- 研究属性
justify-content
值对对齐方式的影响- 当justify-content值为flex-start,即在上述代码中加入
.box { width: 400px; height: 200px; background: #000; display: flex; flex-direction: row; justify-content: flex-start; }
- 当justify-content值为flex-end,即将上述代码改变
.box { .... justify-content: flex-end; }
- 当justify-content值为flex-end,即将上述代码改变
.box { .... justify-content: center; }
- 当justify-content值为space-between,即将上述代码改变
.box { .... justify-content: space-between; }
- 当justify-content值为space-around,即将上述代码改变
.box { .... justify-content: space-around; }
- 在主轴方向上的小应用
我们要实现两组元素分别靠左和靠右对齐
// html
<div class="box">
<div class="box1">box1</div>
<div class="box2">box2</div>
<div class="box3">box3</div>
</div>
// css
.box {
width: 400px;
height: 200px;
border: 1px solid #000;
display: flex;
}
.box div {
width: 100px;
}
.box1 {
border: 1px solid red;
}
.box2 {
border: 1px solid blue;
}
.box3 {
border: 1px solid green;
margin-left: auto;
}
在主轴方向上,我们可以用margin-left
属性实现这样一个效果,这个效果在应用上也非常广泛,如果在3号元素后面还有很多元素,我们也要实现3号元素开始全部向右对齐,我们同上面的办法,在3号元素上加上margin-left:auto
即可