背景
flex 属性,在布局方面做了非常大的改进,使得我们对多个元素之间的布局排列变得十分灵活,适应性非常强。其强大的伸缩性和自适应性,在网页开中可以发挥极大的作用。
flex 布局的优势
float 属性的元素会脱离文档流,而且会涉及到各种 BFC、清除浮动的问题。浮动相关的问题,比较麻烦,但有了 flex 布局之后,这些问题都不存在的。
flex 布局的缺点
flex存在兼容性问题,flex 布局不支持 IE9 及以下的版本;IE10及以上也只是部分支持。如果你的页面不需要处理 IE浏览器的兼容性问题,则可以放心的去使用 flex 布局。
但是,比如网易,京东、淘宝这样的大型网站,这些网站为了兼容低版本的 IE 浏览器,暂时还不敢尝试使用 flex 布局
处理兼容性问题:常见私有前缀
-webkit-: 谷歌 苹果
-moz-:火狐
-ms-:IE
-o-:欧朋
flex 弹性盒子
主要指的的是使用 display:flex 或 display:inline-flex 声明的父容器
flex 弹性盒子
指的是父容器里面的子元素们(父容器被声明为 flex 盒子的情况下)。
主轴和侧轴
-
主轴:flex容器的主轴,默认是水平方向,从左向右。
-
侧轴:与主轴垂直的轴称作侧轴,默认是垂直方向,从上往下。
-
主轴和侧轴并不是固定不变的,可以通过
flex-direction更换方向
flex 弹性盒子
使用display:flex声明一个父容器为弹性盒子,来调整子元素的弹性布局
flex-direction 属性
flex-direction:用于设置盒子中子元素的排列方向。属性值可以是:
| 属性值 | 描述 |
|---|---|
| row | 从左到右水平排列子元素(默认值) |
| column | 从上到下垂直排列子元素 |
| row-reverse | 从右向左排列子元素 |
| column-reverse | 从下到上垂直排列子元素 |
注:默认自左向右
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
body{
background-color: #eee;
font-family: "Microsoft Yahei";
font-size:22px;
}
h3{
font-weight: normal;
}
section{
width: 1000px;
margin:40px auto;
}
ul{
background-color: #fff;
border: 1px solid #ccc;
}
ul li{
width: 200px;
height: 200px;
background-color: red;
margin:10px;
}
section:nth-child(1) ul{
overflow: hidden; /* 清除浮动 */
}
section:nth-child(1) ul li{
float: left;
}
/* 设置伸缩盒子*/
section:nth-child(2) ul{
display: flex;
}
section:nth-child(3) ul{
/* 设置伸缩布局*/
display: flex;
/* 设置主轴方向*/
flex-direction: row;
}
section:nth-child(4) ul{
/* 设置伸缩布局*/
display: flex;
/* 设置主轴方向 :水平翻转*/
flex-direction: row-reverse;
}
section:nth-child(5) ul{
/* 设置伸缩布局*/
display: flex;
/* 设置主轴方向 :垂直*/
flex-direction: column;
}
section:nth-child(6) ul{
/* 设置伸缩布局*/
display: flex;
/* 设置主轴方向 :垂直*/
flex-direction: column-reverse;
}
</style>
</head>
<body>
<section>
<h3>传统布局</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</section>
<section>
<h3>伸缩布局 display:flex</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</section>
<section>
<h3>主轴方向 flex-direction:row</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</section>
<section>
<h3>主轴方向 flex-direction:row-reverse</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</section>
<section>
<h3>主轴方向 flex-direction:column</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</section>
<section>
<h3>主轴方向 flex-direction:column-reverse</h3>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</section>
</body>
</html>
弹性元素
justify-content:控制子元素在主轴上的排列方式
| 属性值 | 描述 |
|---|---|
| flex-start | 从主轴的起点对齐(默认值) |
| flex-end | 从主轴的终点对齐 |
| center | 居中对齐 |
| space-around | 在父盒子里平分 |
| space-between | 两端对齐 平分 |
align-items 属性
设置子元素在侧轴上的对齐方式
| 属性值 | 描述 |
|---|---|
| flex-start | 从侧轴开始的方向对齐 |
| flex-end | 从侧轴结束的方向对齐 |
| center | 中间对齐 |
| stretch | 拉伸 |