一、flex布局是什么?
flex布局(弹性布局盒模型),主要是给予外部容器有控制内部元素高度和宽度的能力。
flex布局的容器内部的各项称为flex item, flex容器拥有两个两个隐形的轴线(主轴<默认是水平反向>,交叉轴<默认是垂直方向>)。
注: 在flex容器内,即flex item的float,clear、vertical-align属性将失效。
二、有哪些属性?
三、应用
1 . flex-direction: 定义主轴的方向
以下代码示例基于这段代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
html, body {
height: 100%;
}
.box {
display: flex;
flex-direction: row-reverse; // 默认是row
// flex-direction: column-reverse; // 默认是row
// flex-direction: column; // 默认是row
}
.same {
width: 40px;
height: 40px;
color: #fff;
}
.one {
background: red;
}
.two {
background: blue;
}
.three {
background: purple;
}
</style>
</head>
<body>
<div class="box">
<div class="same one">
1
</div>
<div class="same two">
2
</div>
<div class="same three">
3
</div>
</div>
</body>
</html>
效果分别如下:
row:
row-reverse:
column:
column-reverse:
2 . flex-wrap: 定义如何换行
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
html, body {
height: 100%;
}
.box {
display: flex;
flex-wrap: wrap; // 默认nowarp
flex-wrap: wrap-reverse; // 默认nowarp
}
.same {
width: 40px;
height: 40px;
color: #fff;
}
.one {
background: red;
}
.two {
background: blue;
}
.three {
background: purple;
}
</style>
</head>
<body>
<div class="box">
<div class="same one">
1
</div>
<div class="same two">
2
</div>
<div class="same three">
3
</div>
<div class="same one">
4
</div>
<div class="same two">
5
</div>
<div class="same three">
6
</div>
<div class="same one">
7
</div>
<div class="same two">
8
</div>
<div class="same three">
9
</div>
</div>
</body>
</html>
nowrap: 不换行, 根据宽度自动缩放
wrap:
wrap-reverse:
3 . justify-content: 定义主轴对齐方式
注: 该示例中没有设置flex-direction因此主轴是默认的水平方向
.box {
display: flex;
justify-content: flex-end; // 默认flex-start
justify-content: space-around; // 默认flex-start
justify-content: space-between; // 默认flex-start
justify-content: center; // 默认flex-start
}
flex-start:
flex-end:
center:
space-between:
space-around:
4 . align-items: 定义交叉轴对齐方式(默认垂直方向是交叉轴)
.one {
height: 100px;
background: red;
}
.two {
height: 200px;
background: blue;
}
.three {
height: 150px;
background: purple;
}
flex-start:
flex-end:
center:
baseline:
stretch: 如果未设置高度的话, 将会占满整个屏幕
5 . order (定义排列顺序)
.one {
background: red;
order: 2;
}
.two {
background: blue;
order: 3;
}
.three {
background: purple;
order: 1;
}
6 . align-self (允许某个项目与其他项目不一样的对齐方式)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
html, body {
height: 100%;
}
.box {
display: flex;
height: 500px;
align-items: flex-start; // 默认flex-start
}
.same {
width: 40px;
height: 40px;
color: #fff;
}
.one {
height: 100px;
background: red;
}
.two {
height: 200px;
background: blue;
align-self: flex-end;
}
.three {
height: 150px;
background: purple;
}
</style>
</head>
<body>
<div class="box">
<div class="same one">
1
</div>
<div class="same two">
2
</div>
<div class="same three">
3
</div>
</div>
</body>
</html>
参考: