RESPONSIVE_LAYOUT_SOLUTION.md
14.4 KB
主流屏幕自适应布局方案
一、问题描述
1.1 业务需求
在 uni-app x 项目中,需要实现页面布局在不同屏幕尺寸下的自适应显示,适配主流设备屏幕:
- 手机端:320px - 480px(小屏手机)、480px - 768px(常规手机)、768px - 1024px(大屏手机/小平板)
- 平板端:1024px - 1920px(平板、大屏设备)
- 横屏模式:需要适配横屏布局
1.2 技术限制
uni-app x 不支持 CSS 媒体查询(@media)
根据 uni-app x 官方规范(.cursor/rules/ucss.mdc):
-
@media查询不在支持的 at-rules 列表中 - 官方明确说明:如需使用
@media适配不同屏幕,改用 UTS 代码实现,先通过 APIuni.getWindowInfo获取屏幕宽度,再通过代码进行适配
CSS 单位限制
- 仅支持
px、rpx、百分比 - 不支持
vh、vw、rem、em(除 line-height 外) -
rpx使用限制:除非 width 需要根据屏幕宽度而变化才使用 rpx,其他场景不使用 rpx
1.3 当前问题
-
无法使用传统媒体查询方案:不能使用
@media (min-width: 768px)等 CSS 媒体查询语法 -
固定 px 值在大屏设备显示异常:使用固定
px值(如font-size: 12px)在小屏正常,但在大屏(如 4K 屏幕、平板)上显示过小 - 布局适配困难:需要根据不同屏幕宽度调整布局(如手机单列、平板多列),但缺少便捷的适配机制
-
响应式字体大小:字体大小需要根据屏幕尺寸动态调整,但无法使用
rem或vw单位
1.4 影响范围
- 用户体验:大屏设备上字体过小、布局不合理
- 开发效率:需要手动为不同屏幕编写多套样式
- 维护成本:样式代码分散,难以统一管理
二、解决方案
2.1 核心思路
使用 UTS 代码 + 动态样式 + px/flex/百分比组合
-
获取屏幕信息:使用
uni.getWindowInfo()获取屏幕宽度、高度等信息 - 动态计算样式值:在 UTS 代码中根据屏幕宽度计算字体大小、间距、布局参数
-
绑定动态样式:使用
:style或动态 class 将计算后的样式值绑定到组件 -
组合使用单位:
- px:固定尺寸(图标、边框、最小间距)
- flex:弹性布局(自适应容器、比例分配)
- 百分比:相对父容器(宽度、高度、内边距)
2.2 实现方案
方案 1:工具函数 + 动态样式(推荐)
创建屏幕适配工具函数
// utils/screen-adapt.uts
/**
* 屏幕信息接口
*/
export interface ScreenInfo {
width: number
height: number
pixelRatio: number
screenWidth: number
screenHeight: number
}
/**
* 获取屏幕信息
*/
export function getScreenInfo(): ScreenInfo {
const windowInfo = uni.getWindowInfo()
return {
width: windowInfo.windowWidth,
height: windowInfo.windowHeight,
pixelRatio: windowInfo.pixelRatio,
screenWidth: windowInfo.screenWidth,
screenHeight: windowInfo.screenHeight
}
}
/**
* 屏幕尺寸分类
*/
export type ScreenSize = 'small' | 'medium' | 'large' | 'xlarge'
/**
* 获取屏幕尺寸分类
* - small: < 480px(小屏手机)
* - medium: 480px - 768px(常规手机)
* - large: 768px - 1024px(大屏手机/小平板)
* - xlarge: >= 1024px(平板、大屏设备)
*/
export function getScreenSize(): ScreenSize {
const width = getScreenInfo().width
if (width < 480) {
return 'small'
} else if (width < 768) {
return 'medium'
} else if (width < 1024) {
return 'large'
} else {
return 'xlarge'
}
}
/**
* 响应式字体大小
* @param baseSize 基础字体大小(设计稿 750px 下的值)
* @param minSize 最小字体大小(px)
* @param maxSize 最大字体大小(px)
* @returns 计算后的字体大小(px)
*/
export function responsiveFontSize(baseSize: number, minSize: number = 12, maxSize: number = 48): number {
const screenInfo = getScreenInfo()
const screenWidth = screenInfo.width
// 设计稿基准宽度(通常为 375px 或 750px)
const designWidth = 375
// 计算缩放比例(限制在合理范围内)
const scale = screenWidth / designWidth
const scaledSize = baseSize * scale
// 限制在最小值和最大值之间
if (scaledSize < minSize) {
return minSize
} else if (scaledSize > maxSize) {
return maxSize
}
return Math.round(scaledSize)
}
/**
* 响应式间距
* @param baseSpacing 基础间距(设计稿 750px 下的值)
* @param minSpacing 最小间距(px)
* @param maxSpacing 最大间距(px)
* @returns 计算后的间距(px)
*/
export function responsiveSpacing(baseSpacing: number, minSpacing: number = 4, maxSpacing: number = 64): number {
const screenInfo = getScreenInfo()
const screenWidth = screenInfo.width
const designWidth = 375
const scale = screenWidth / designWidth
const scaledSpacing = baseSpacing * scale
if (scaledSpacing < minSpacing) {
return minSpacing
} else if (scaledSpacing > maxSpacing) {
return maxSpacing
}
return Math.round(scaledSpacing)
}
/**
* 响应式宽度(用于固定宽度元素)
* @param baseWidth 基础宽度(设计稿 750px 下的值)
* @returns 计算后的宽度(px)
*/
export function responsiveWidth(baseWidth: number): number {
const screenInfo = getScreenInfo()
const screenWidth = screenInfo.width
const designWidth = 375
return Math.round(baseWidth * (screenWidth / designWidth))
}
/**
* 判断是否为横屏
*/
export function isLandscape(): boolean {
const screenInfo = getScreenInfo()
return screenInfo.width > screenInfo.height
}
/**
* 判断是否为平板尺寸
*/
export function isTablet(): boolean {
const screenSize = getScreenSize()
return screenSize === 'large' || screenSize === 'xlarge'
}
在页面中使用
<template>
<view class="container">
<!-- 使用动态样式 -->
<text :style="{ fontSize: fontSize + 'px', padding: padding + 'px' }">
响应式文本
</text>
<!-- 使用动态 class -->
<view :class="containerClass">
<view class="item" v-for="item in list" :key="item.id">
{{ item.name }}
</view>
</view>
</view>
</template>
<script setup lang="uts">
import { ref, computed, onMounted } from 'vue'
import { getScreenSize, responsiveFontSize, responsiveSpacing, isTablet } from '@/utils/screen-adapt.uts'
// 响应式字体大小
const fontSize = ref<number>(14)
const padding = ref<number>(16)
// 动态 class
const containerClass = computed<string>(() => {
const size = getScreenSize()
return `container-${size}`
})
// 初始化时计算样式值
onMounted(() => {
// 基础字体 14px(设计稿 375px),最小 12px,最大 20px
fontSize.value = responsiveFontSize(14, 12, 20)
// 基础间距 16px(设计稿 375px),最小 12px,最大 24px
padding.value = responsiveSpacing(16, 12, 24)
// 根据屏幕尺寸调整布局
if (isTablet()) {
// 平板布局逻辑
console.log('平板布局')
}
})
</script>
<style>
.container {
display: flex;
flex-direction: column;
}
/* 小屏:单列布局 */
.container-small {
flex-direction: column;
}
/* 中屏:单列布局 */
.container-medium {
flex-direction: column;
}
/* 大屏:两列布局 */
.container-large {
flex-direction: row;
flex-wrap: wrap;
}
/* 超大屏:三列布局 */
.container-xlarge {
flex-direction: row;
flex-wrap: wrap;
}
.item {
/* 使用 flex 自适应 */
flex: 1;
min-width: 0;
}
/* 大屏设备:固定最小宽度 */
.container-large .item,
.container-xlarge .item {
flex: 0 0 calc(50% - 8px); /* 两列,间距 16px */
min-width: 200px;
}
</style>
方案 2:Composable 函数封装(Vue 3 Composition API)
创建响应式布局 Composable
// composables/useResponsive.uts
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { getScreenInfo, getScreenSize, responsiveFontSize, responsiveSpacing, isTablet, isLandscape } from '@/utils/screen-adapt.uts'
/**
* 响应式布局 Composable
*/
export function useResponsive() {
const screenWidth = ref<number>(375)
const screenHeight = ref<number>(667)
const screenSize = ref<'small' | 'medium' | 'large' | 'xlarge'>('medium')
const isTabletMode = ref<boolean>(false)
const isLandscapeMode = ref<boolean>(false)
/**
* 更新屏幕信息
*/
function updateScreenInfo() {
const info = getScreenInfo()
screenWidth.value = info.width
screenHeight.value = info.height
screenSize.value = getScreenSize()
isTabletMode.value = isTablet()
isLandscapeMode.value = isLandscape()
}
/**
* 响应式字体大小
*/
const fontSize = computed(() => {
return (baseSize: number, minSize: number = 12, maxSize: number = 48) => {
return responsiveFontSize(baseSize, minSize, maxSize)
}
})
/**
* 响应式间距
*/
const spacing = computed(() => {
return (baseSpacing: number, minSpacing: number = 4, maxSpacing: number = 64) => {
return responsiveSpacing(baseSpacing, minSpacing, maxSpacing)
}
})
onMounted(() => {
updateScreenInfo()
// 监听屏幕旋转(如果需要)
// uni.onWindowResize(() => {
// updateScreenInfo()
// })
})
return {
screenWidth,
screenHeight,
screenSize,
isTabletMode,
isLandscapeMode,
fontSize,
spacing,
updateScreenInfo
}
}
在页面中使用
<script setup lang="uts">
import { computed } from 'vue'
import { useResponsive } from '@/composables/useResponsive.uts'
const { screenSize, isTabletMode, fontSize, spacing } = useResponsive()
// 动态样式对象
const textStyle = computed(() => {
return {
fontSize: fontSize.value(14, 12, 20) + 'px',
padding: spacing.value(16, 12, 24) + 'px'
}
})
// 动态 class
const containerClass = computed(() => {
return `container container-${screenSize.value} ${isTabletMode.value ? 'tablet' : 'mobile'}`
})
</script>
方案 3:CSS 变量 + UTS 计算(适合全局样式)
在 App.uvue 中设置全局 CSS 变量
<script setup lang="uts">
import { onMounted } from 'vue'
import { getScreenInfo, responsiveFontSize, responsiveSpacing } from '@/utils/screen-adapt.uts'
onMounted(() => {
const screenInfo = getScreenInfo()
// 计算全局样式变量
const baseFontSize = responsiveFontSize(14, 12, 20)
const baseSpacing = responsiveSpacing(16, 12, 24)
const screenWidth = screenInfo.width
// 设置 CSS 变量(通过 :root 或全局样式)
// 注意:uni-app x 可能不支持动态设置 CSS 变量,需要结合方案 1 使用
})
</script>
在 common.css 中定义响应式工具类
/* common.css */
/* 响应式字体大小(需要配合 UTS 计算) */
.text-xs { font-size: 12px; }
.text-sm { font-size: 14px; }
.text-base { font-size: 16px; }
.text-lg { font-size: 18px; }
.text-xl { font-size: 20px; }
/* 响应式间距 */
.p-1 { padding: 4px; }
.p-2 { padding: 8px; }
.p-3 { padding: 12px; }
.p-4 { padding: 16px; }
.p-5 { padding: 20px; }
.p-6 { padding: 24px; }
/* 响应式布局 */
.flex-col-mobile {
flex-direction: column;
}
.flex-row-tablet {
flex-direction: row;
}
/* 使用条件编译(如果需要) */
/* #ifdef APP */
/* 平板布局 */
@media (min-width: 768px) {
.flex-row-tablet {
flex-direction: row;
}
}
/* #endif */
注意:uni-app x 不支持 @media,上述代码中的 @media 仅作为注释说明,实际需要使用方案 1 或方案 2。
2.3 最佳实践
1. 字体大小适配
// 设计稿 375px,字体 14px
// 小屏(320px):12px(最小值)
// 常规(375px):14px(基准值)
// 大屏(768px):18px(按比例缩放)
// 超大屏(1024px):20px(最大值)
const fontSize = responsiveFontSize(14, 12, 20)
2. 布局适配
<template>
<view :class="['list-container', `list-${screenSize}`]">
<view class="list-item" v-for="item in list" :key="item.id">
{{ item.name }}
</view>
</view>
</template>
<style>
.list-container {
display: flex;
flex-wrap: wrap;
}
/* 手机:单列 */
.list-small .list-item,
.list-medium .list-item {
width: 100%;
}
/* 大屏手机/小平板:两列 */
.list-large .list-item {
width: calc(50% - 8px);
margin-right: 16px;
}
/* 平板:三列 */
.list-xlarge .list-item {
width: calc(33.333% - 11px);
margin-right: 16px;
}
</style>
3. 间距适配
// 使用 flex + 百分比 + margin 组合
// 避免使用 calc(),改用 margin 实现间距
const itemMargin = responsiveSpacing(8, 4, 16) // 基础 8px,最小 4px,最大 16px
4. 固定尺寸元素
// 图标、按钮等固定尺寸,使用 px
// 但可以根据屏幕尺寸微调
const iconSize = isTablet() ? 24 : 20 // 平板 24px,手机 20px
2.4 注意事项
-
性能优化:
- 屏幕信息获取在
onMounted时执行一次即可 - 避免在
computed中频繁调用uni.getWindowInfo() - 使用
ref缓存计算结果
- 屏幕信息获取在
-
屏幕旋转处理:
- 如果需要支持屏幕旋转,监听
uni.onWindowResize()事件 - 重新计算样式值
- 如果需要支持屏幕旋转,监听
-
设计稿基准:
- 统一设计稿基准宽度(如 375px 或 750px)
- 所有计算基于同一基准,避免混乱
-
rpx 使用限制:
- 仅在 width 需要根据屏幕宽度变化时使用 rpx
- 其他场景使用 px + flex + 百分比
-
测试覆盖:
- 测试不同屏幕尺寸(320px、375px、414px、768px、1024px、1920px)
- 测试横屏模式
- 测试平板设备
三、实施步骤
3.1 创建工具函数
- 创建
utils/screen-adapt.uts文件 - 实现屏幕信息获取、尺寸分类、响应式计算函数
3.2 在页面中应用
- 导入工具函数
- 在
onMounted中计算初始样式值 - 使用
:style或动态 class 绑定样式
3.3 测试验证
- 在不同屏幕尺寸设备上测试
- 验证字体大小、间距、布局是否正常
- 测试横屏模式
3.4 优化迭代
- 根据实际效果调整缩放算法
- 优化性能(缓存计算结果)
- 提取公共逻辑为 Composable
四、总结
核心要点:
-
❌ 不支持@media媒体查询 -
✅ 使用uni.getWindowInfo()+ UTS 代码实现适配 -
✅ 组合使用 px(固定)+ flex(弹性)+ 百分比(相对父容器) -
✅ 动态计算 字体大小、间距等响应式值 -
✅ 统一基准 设计稿宽度,避免混乱
推荐方案:方案 1(工具函数 + 动态样式),简单直接,易于维护。
文档版本:v1.0
创建日期:2026-01-23
适用框架:uni-app x
参考规范:.cursor/rules/ucss.mdc