3月 042025
一、Flex布局基础
Flex布局由 容器(父元素) 和 项目(子元素) 构成。通过 display: flex
声明容器。
1 2 3 4 5 6 7 8 9 10 11 12 |
<template> <view class="container"> <view class="item">1</view> <view class="item">2</view> </view> </template> <style> .container { display: flex; /* 启用 Flex 布局 */ } </style> |
二、(父)容器属性详解
1. flex-direction
定义主轴方向(项目的排列方向)
值 | 描述 |
---|---|
row (默认) | 水平排列(左→右) |
row-reverse | 水平反向(右→左) |
column | 垂直排列(上→下) |
column-reverse | 垂直反向(下→上) |
1 2 3 4 5 6 7 8 9 10 11 |
<view class="container column"> <view class="item">1</view> <view class="item">2</view> </view> <style> .column { flex-direction: column; /* 垂直排列 */ height: 300rpx; /* 需要指定高度 */ } </style> |
2. justify-content
定义主轴对齐方式
值 | 描述 |
---|---|
flex-start | 向主轴起点对齐(默认) |
flex-end | 向主轴终点对齐 |
center | 居中对齐 |
space-between | 两端对齐,间隔相等 |
space-around | 每个项目两侧间隔相等 |
3. align-items
定义交叉轴对齐方式
值 | 描述 |
---|---|
stretch | 拉伸填满容器(默认) |
flex-start | 向交叉轴起点对齐 |
flex-end | 向交叉轴终点对齐 |
center | 居中对齐 |
4. flex-wrap
定义是否换行
值 | 描述 |
---|---|
nowrap | 不换行(默认) |
wrap | 换行 |
wrap-reverse | 反向换行 |
5. align-content
多行项目的交叉轴对齐方式
值 | 描述 |
---|---|
stretch | 拉伸填满容器(默认) |
flex-start | 向交叉轴起点对齐 |
center | 居中对齐 |
space-between | 两端对齐 |
三、项目属性
1. flex-grow
定义项目的放大比例(默认0)
结果:剩余空间按1:2分配
2. flex-shrink
定义项目的缩小比例(默认1)
1 2 3 4 5 6 7 8 |
<view class="container"> <view class="item shrink0">1(不缩小)</view> <view class="item">2</view> </view> <style> .shrink0 { flex-shrink: 0; } .item { width: 400rpx; } /* 故意超出容器宽度 */ </style> |
结果:第一个元素保持宽度,第二个被压缩
3. align-self
单个项目的交叉轴对齐方式
1 2 3 4 5 6 7 8 9 |
<view class="container"> <view class="item self-center">居中对齐</view> <view class="item">默认对齐</view> </view> <style> .self-center { align-self: center; } </style> |
四、综合示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<template> <view class="container"> <view class="item header">Header</view> <view class="item main">Main Content</view> <view class="item footer">Footer</view> </view> </template> <style> .container { display: flex; flex-direction: column; height: 100vh; } .header, .footer { height: 100rpx; background: #eee; } .main { flex: 1; background: #f0f0f0; } </style> |
结果:经典的头-主体-底布局
五、注意事项
- 在微信小程序中需添加
overflow: hidden
解决兼容性问题 - 使用
rpx
单位保证多端适配 - 推荐配合
box-sizing: border-box
使用
Sorry, the comment form is closed at this time.