手把手教你学Flex布局
程序员文章站
2022-06-06 09:57:20
...
手把手教你学Flex布局
一、背景
Flex布局`是由CSS3提出的一种新的更加灵活的布局方式,适用于移动端,和PC端兼容性要求不高的项目上。
二、Flex布局的基本概念
-
Flex容器:声明Flex布局的父级容器
-
Flex项目:声明Flex布局的父级容器下的子元素
-
主轴(main axis)和侧轴(cross axis):Flex容器中包含两个相互垂直的轴
-
主轴(main size)/侧轴(cross size)长度:占据的主轴空间叫做主轴长度 (main size), 占据的副轴空间叫做副轴长度 (cross size).
-
Flex项目默认沿主轴从**主轴起点 (main start)到主轴终点 (main end)**依次排布
-
如果flex容器包含多行flex元素, 则**flex行 (flex lines)沿副轴从副轴起点 (cross start)到副轴终点 (cross end)**依次排布
三、Flex布局的兼容性
由上图can i use可以看出,对于PC端,Flex布局仍有不小的兼容性问题存在,flex属性至少支持IE10+,所以根据项目要求慎用Flex。
四、Flex布局各个属性详解
—— Flex-box容器上的属性
- flex-direction:
<!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">
<link rel="stylesheet" href="./css/index.css">
<title>Document</title>
</head>
<body>
<div class="flex-box">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
<div class="flex-item">5</div>
</div>
<div class="flex-box flex-box1">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
<div class="flex-item">5</div>
</div>
<div class="flex-box flex-box2">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
<div class="flex-item">5</div>
</div>
<div class="flex-box flex-box3">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
<div class="flex-item">5</div>
</div>
</body>
</html>
*{
margin: 0;
padding: 0;
}
.flex-box{
margin: 80px auto;
display: flex;
width: 500px;
color: #000;
box-shadow: 0 0 1rem #100e17;
.flex-item{
width: 120px;
height: 60px;
line-height: 60px;
text-align: center;
font-size: 18px;
}
.flex-item:nth-child(1){
background-color: #1abc9c;
}
.flex-item:nth-child(2){
background-color: #2ecc71;
}
.flex-item:nth-child(3){
background-color: #3498db;
}
.flex-item:nth-child(4){
background-color: #9b59b6;
}
.flex-item:nth-child(5){
background-color: #34495e;
}
}
.flex-box1{
flex-direction: row-reverse;
}
.flex-box2{
flex-direction: column;
}
.flex-box3{
flex-direction: column-reverse;
}
-
flex-wrap
-
flex-flow
-
justify-content
-
align-items
-
align-content
.flex-box{ display:flex; } //width:100%,相当于display:block
.flex-box{ display:inline-flex; } //width由flex-item撑开,相当于display:inline-block
注意: Flex-item有以下2个特点
1、css 列(CSS columns)在flex-box中不起作用
2、float`, `clear` and `vertical-align` 在flex-item中不起作用
- flex-direction:主轴方向,默认row