uniapp项目小程序中如何使用媒介查询实现响应式布局

在uniapp开发小程序时,如何使用媒介查询(@media)实现响应式布局?官方文档提到小程序支持rpx单位,但直接写CSS媒介查询似乎不生效。请问具体应该如何配置?是否需要在page.json或uni.scss中额外设置?能否提供在小程序环境中生效的代码示例?

2 回复

在uniapp小程序中,可使用uni.getSystemInfoSync()获取设备信息,根据屏幕宽度设置不同样式:

const systemInfo = uni.getSystemInfoSync()
const screenWidth = systemInfo.screenWidth

if(screenWidth < 375) {
  // 小屏样式
} else if(screenWidth >= 375 && screenWidth < 414) {
  // 中屏样式
} else {
  // 大屏样式
}

也可使用rpx单位自动适配不同屏幕。


在UniApp小程序中,可以通过以下方式实现响应式布局:

1. 使用CSS媒体查询

<style>标签中定义不同屏幕尺寸的样式:

/* 默认样式 */
.container {
  padding: 20rpx;
}

/* 屏幕宽度 ≥ 768px 时的样式 */
@media screen and (min-width: 768px) {
  .container {
    padding: 40rpx;
    background-color: #f0f0f0;
  }
}

/* 屏幕宽度 ≤ 375px 时的样式 */
@media screen and (max-width: 375px) {
  .container {
    padding: 10rpx;
    font-size: 14px;
  }
}

2. 使用rpx单位

UniApp推荐使用rpx作为响应式单位(1rpx ≈ 屏幕宽度/750):

.container {
  width: 750rpx; /* 满屏宽度 */
  font-size: 32rpx; /* 自适应字体大小 */
}

3. 结合Flex布局

.container {
  display: flex;
  flex-direction: column;
}

@media screen and (min-width: 768px) {
  .container {
    flex-direction: row;
  }
}

4. 通过JS检测屏幕尺寸

在Vue中动态计算:

export default {
  data() {
    return {
      windowWidth: 0
    }
  },
  onLoad() {
    this.getScreenSize()
  },
  methods: {
    getScreenSize() {
      const info = uni.getSystemInfoSync()
      this.windowWidth = info.windowWidth
    }
  },
  computed: {
    isMobile() {
      return this.windowWidth < 768
    }
  }
}

注意事项:

  1. 小程序中媒体查询的px单位以物理像素为准
  2. 建议优先使用rpx+Flex布局
  3. 复杂场景可配合使用uni-upgrade-center等官方扩展

推荐组合方案:基础布局使用rpx+Flex,特殊断点需求配合媒体查询实现精细控制。

回到顶部