1. flex 是什么?
flex 是 Flexible Box 的缩写,就是弹性盒子布局.
2. 为什么我们需要 flex?
解决元素居中问题自动弹性伸缩以及适配不同大小的屏幕和移动端
3、如何设置flex布局
与grid类似,flex也分为块级元素和行内元素两种,分别为display:flex(块级元素)与display:inline-flex(行内元素)。
我们先来举个例子看看flex有何作用,首先,我们先来看未设置flex布局时的样子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<STyle>
.container{
border: 10px solid black;
height: 500px;
width: 1000px;
}
.container div{
width: 500px;
}
.item1{
background-color: pink;
}
.item-2{
background-color: purple;
}
.item-3{
background-color: red;
}
.item-4{
background-color: rosybrown;
}
.item-5{
background-color: salmon;
}
.item-6{
background-color: slateblue;
}
</STyle>
<body>
<div class="container">
<div class="item1">1</div>
<div class="item-2">2</div>
<div class="item-3">3</div>
<div class="item-4">4</div>
<div class="item-5">5</div>
<div class="item-6">6</div>
</div>
</body>
</html>
效果如图:
当设置flex后为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.container{
border: 10px solid black;
height: 500px;
width: 1000px;
display: flex;
align-content: stretch;
}
.container div{
width: 500px;
}
.item1{
background-color: pink;
}
.item-2{
background-color: purple;
}
.item-3{
background-color: red;
}
.item-4{
background-color: rosybrown;
}
.item-5{
background-color: salmon;
}
.item-6{
background-color: slateblue;
}
</STyle>
<body>
<div class="container">
<div class="item1">1</div>
<div class="item-2">2</div>
<div class="item-3">3</div>
<div class="item-4">4</div>
<div class="item-5">5</div>
<div class="item-6">6</div>
</div>
</body>
</html>
在设置了flex布局6个div沿着主轴方向排列(沿着主轴方向排列一般为flex的默认方式)
4、容器属性
4.1排列方向:flex-direction
row | 横向从左到右排列(左对齐)。 |
row-reverse | 对齐方式与row相反。 |
column | 纵向从上往下排列(顶对齐)。 |
column-reverse | 对齐方式与column相反。 |
接下来我们一一举例来说明这几种属性:
4.1.1、row
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.container{
border: 10px solid black;
height: 500px;
width: 100%;
display: flex;
flex-direction: row;
}
.container div{
width: 500px;
}
.item1{
background-color: pink;
/* 允许项目进行收缩 */
}
.item-2{
background-color: purple;
}
.item-3{
background-color: red;
}
.item-4{
background-color: rosybrown;
}
.item-5{
background-color: salmon;
}
.item-6{
background-color: slateblue;
}
</STyle>
<body>
<div class="container">
<div class="item1">1</div>
<div