🚀 你想知道的Flex布局都在这里(含资料) 🚀

628 阅读3分钟

前言

一直以来,在做移动端项目的过程中,经常会用flex布局解决移动端场景下的屏幕适配,使得flex布局有了大展拳脚的地方,因此flex布局已经是一个前端开发者必须要掌握的css技能了,于是自己花了一些时间做了一些总结,也整理了一些资料,希望能给大家有所帮助

相关资料

基本概念

image.png

轴与容器的关系如下

image.png

定义主轴方向,默认情况下主轴为从左到右,

flex-direction: row | row-reverse | column | column-reverse

image.png

image.png

image.png

image.png

设置父容器

justify-content

justify-content 在主轴方向上的对齐方式

justify-content: flex-start | flex-end | center | space-between | space-around

justify-content: flex-start

image.png

justify-content: flex-end

image.png

justify-content: center

image.png

justify-content: space-between

image.png

justify-content: space-around

image.png

align-items

align-items 在交叉轴上的对齐方式

align-items: flex-start | flex-end | center | baseline | stretch

align-items: flex-start

image.png

align-items: flex-end

image.png

align-items: center

image.png

align-items: baseline

image.png

align-items: stretch

撑满交叉轴

image.png

flex-wrap

flex-wrap 是否换行

flex-wrap: wrap | nowrap | wrap-reverse

flex-wrap: wrap

不换行 image.png

flex-wrap: nowrap

换行 image.png

flex-wrap: wrap-reverse

image.png

flex-flow

flex-flow flex-direction & flex-wrap简写

align-content

align-content 多行子容器在交叉轴上的对齐方式,首先的前提是它要满足换行

align-content: flex-start | flex-end | center | space-between | space-around | stretch

align-content: flex-start

image.png

align-content: flex-end

image.png

align-content: center

image.png

align-content: space-between

image.png

align-content: space-around

image.png

设置子容器

flex

子容器是可以有弹性的,如果是数字无单位,则会变为弹性子容器,如果是带有px,则按照像素来分配

设置所有子容器flex: 1,它们是均分的

image.png

当设置第二个子容器flex: 2,其他为1,那么第二个子容器是其他子容器的两倍

image.png

如果设置flex: 0那么按照设置子容器的宽度width为准

align-self

单独设置子容器的交叉轴排列方式

align-self: flex-start | flex-end | center | baseline | stretch

比如我单独设置第一个子容器align-self: center image.png

flex-basis

表示当子容器不伸缩的状态时,也就是没有设置flex: 数字的弹性情况下的原始尺寸

flex-grow

弹性伸展比例,当设置此样式,当前子容器就会撑满主轴宽度

设置第一个子容器flex-grow: 2, 第二个子容器flex-grow: 1,那么它们撑开的宽度是以2:1来进行分配的

也就是说它们应该是将剩余的宽度分为了三份,如果子容器width: 20%,那么它们的宽度应该为

(20% + 2 * 分配份数) : (20% + 1 * 分配份数)

image.png

flex-shrink

超出比例的收缩分配 如果子容器设置的为固定宽度,当设置此样式则会按照一定的比例依次减少宽度,与上面的原理是一样的 假设有三个子容器width: 50%,第一个flex-shrink: 0,第二个flex-shrink: 2,第三个flex-shrink: 3,那么第一个肯定是要全部占满,它是不可能缩小宽度的,因为它不需要分配宽度去缩小,那么第二个和第三个就得按照比例去减少自己的宽度了

image.png

order

自定义排序 这个很好理解,设置order可以按照由小到大进行排列

设置第二个子容器order: -1

image.png

第二个子容器就跑到最前了,是不是很简单~