1.布局原理
flex 是 flexible Box 的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性,任何一个容器都可以 指定为 flex 布局。
当我们为父盒子设为 flex 布局以后,子元素的 float、clear 和 vertical-align 属性将失效。
伸缩布局 = 弹性布局 = 伸缩盒布局 = 弹性盒布局 =flex布局
2.flex布局父项常见属性
flex-direction:
主轴和侧轴:
默认主轴是x轴方向,水平向右;
默认侧轴是y轴方向,水平向下
<style>div {/* 给父级添加flex属性 */display: flex;width: 800px;height: 300px;background-color: pink;/* 默认的主轴是 x 轴 行 row 那么y轴就是侧轴喽 *//* 我们的元素是跟着主轴来排列的 *//* flex-direction: row; *//* 简单了解 翻转 */flex-direction: row-reverse;/* 我们可以把我们的主轴设置为 y轴 那么 x 轴就成了侧轴 */flex-direction: column;}div span {width: 150px;height: 100px;background-color: purple;}</style>
justify-content(设置主轴上的子元素的排列方式)
flex-wrap 设置子元素是否换行
默认情况下,项目都排在一条线(又称”轴线”)上。flex-wrap属性定义,flex布局中默认是不换行的
属性值:no-wrap(换行)、wrap(默认值换行)
align-items
设置侧轴上的子元素排列方式(单行 )
div {display: flex;width: 800px;height: 400px;background-color: pink;/* 默认的主轴是 x 轴 row */flex-direction: column;justify-content: center;/* 我们需要一个侧轴居中 *//* 拉伸,但是子盒子不要给高度 /* align-items: stretch; */align-items: center;/* align-content: center; */
}
align-content
适应于换行(多行)的情况下,可设置上对齐、下对齐、居中、拉伸以及平均分配剩余空间等属性值。
单行找align-item多行找align-conten
flex:属性定义子项目分配剩余空间,用flex来表示占多少份数
align-self:控制子项在自己在侧轴上的排列方式
order:定义项目的排列顺序
<style>section {display: flex;width: 60%;height: 150px;background-color: pink;margin: 100px auto;/* justify-content: center; *//* align-items: center; */}section div {background-color: purple;margin-right: 5px;width: 100px;height: 50px;}section div:nth-child(2) {/* 默认是0 -1比0小所以在前面 */order: -1;background-color: greenyellow;}section div:nth-child(3) {align-self: flex-end;}</style>
背景渐变必须添加浏览器私有前缀
/* background: -webkit-linear-gradient(left, red, blue); */
/* background: -webkit-linear-gradient(red, blue); */
background: -webkit-linear-gradient(top left, rgb(22, 173, 67), rgb(71, 10, 212));