flex
//容器属性
flex-direction
flex-wrap
flex-flow//flex-direction属性和flex-wrap属性的简写形式,默认值为row nowrap
justify-content
align-items//flex-start、flex-end、center、baseline、stretch
align-content//属性定义了多根轴线的对齐方式。如果项目只有一根轴线,该属性不起作用
//项目属性
order//设置顺序
flex-grow//设置放大比例(剩余空间分配比例(默认为0,不扩展))
flex-shrink//宽度不够时设置缩小比列(空间不足时收缩比例(默认为1,可收缩))
flex-basis//项目在分配剩余空间前的初始大小
flex//flex-grow, flex-shrink 和 flex-basis的简写,默认值为0 1 auto。后两个属性可选
align-self//允许单个项目有与其他项目不一样的对齐方式
常见问题:
如何实现水平垂直居中?
.container {
display: flex;
justify-content: center; /* 主轴居中 */
align-items: center; /* 交叉轴居中 */
}
如何实现「圣杯布局」(Header + Footer + 自适应内容区)?
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.header { height: 60px; }
.content { flex: 1; } /* 占据剩余空间 */
.footer { height: 100px; }
flex-basis 和 width 的优先级
若 flex-direction: row,flex-basis 优先级高于 width
若 flex-basis 为 auto,则使用 width 的值
例外:min-width/max-width 会限制 flex-basis。
flex-shrink: 0 的作用
禁止项目在空间不足时收缩,常用于固定侧边栏:
.sidebar {
flex: 0 0 250px; /* flex-grow:0, flex-shrink:0, flex-basis:250px */
}
为什么设置 flex:1 的项目宽度不一致?
原因:若项目内容长度差异大,且 flex-basis:0(即 flex:1),浏览器会优先按内容比例分配空间。
解决:设置 min-width: 0 或 overflow: hidden 重置内容最小尺寸。
Flex 布局中 margin: auto 的特殊效果
现象:在 Flex 项目中,margin: auto 会吸收剩余空间,实现特定对齐效果。
示例:单个项目右对齐 → margin-left: auto。