2.4 Flex 弹性布局实操,实现从右到左排列 一、案例简介本次作业为《案例 2.4 Flex 弹性布局》使用 Flex 弹性布局完成页面盒子排列。基础案例默认第一行元素从左向右均匀排布作业要求在此基础上修改代码把第一行布局改为从右到左均匀排列。Flex 是小程序、网页开发中最常用的布局方案可以快速实现水平、垂直方向的元素对齐与排序。本案例采用微信小程序 wxmlwxss 编写最后打包代码上传同时撰写本篇技术博客。二、Flex 核心知识点display:flex开启弹性布局容器直接变为 flex 容器子元素自动成为 flex 项目flex-direction控制主轴方向。row默认从左往右排列row-reverse从右往左排列本次作业修改关键点justify-content主轴上元素对齐方式。space-around/space-between实现水平均匀分布。align-items交叉轴垂直。三、完整小程序代码app.json { pages: [ pages/index/index ], window: { navigationBarTextStyle: black, navigationStyle: custom }, style: v2, sitemapLocation: sitemap.json, lazyCodeLoading: requiredComponents } index.wxml !--index.wxml-- navigation-bar title弹性盒模型 back{{false}} colorblack background#FFF/navigation-bar scroll-view classscrollarea scroll-y typelist view classbox view classtitle水平均匀布局/view view styledisplay: flex;line-height: 120rpx;text-align: center; view stylebackground-color: red;flex-grow: 1;中/view view stylebackground-color:green;flex-grow: 1;华/view view stylebackground-color:blue;flex-grow: 1;民/view view stylebackground-color:purple;flex-grow: 1;族/view /view view classtitle stylemargin-top: 40rpx;左右混合布局/view view styledisplay: flex;text-align: center; view stylebackground-color: red;width: 50%;line-height: 240rpx;强/view view styledisplay: flex;flex-direction: column;flex-grow: 1;line-height: 120rpx; view stylebackground-color: green;国/view view stylebackground-color: blue;梦/view /view /view view classtitle stylemargin-top: 40rpx;上下混合布局/view view styledisplay: flex;flex-direction: column;text-align: center; view stylebackground-color: red;line-height: 120rpx;强/view view styledisplay: flex;line-height: 120rpx; view stylebackground-color:green;flex-grow: 0.5;军/view view stylebackground-color:blue;flex-grow: 1;梦/view /view /view /view /scroll-view index.wxss /**index.wxss**/ page { height: 100vh; display: flex; flex-direction: column; } .scrollarea { flex: 1; overflow-y: hidden; } app.wxss /**app.wxss**/ .container { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: space-between; padding: 200rpx 0; box-sizing: border-box; } .box{ margin: 20rpx; padding: 20rpx; border: 2rpx solid silver; } .title{ font-size: larger; font-weight: bolder; text-align: center; margin-bottom: 30rpx; color: red; }四、运行效果五、总结Flex 弹性布局是前端核心布局技术通过简单属性就可以灵活控制元素排列方向。本次案例重点练习flex-direction属性使用row-reverse实现从右到左布局。