aspect-ratio: 1 / 1样式在部分手机浏览器中失效的问题怎么解决?

发布于:2025-07-19 ⋅ 阅读:(13) ⋅ 点赞:(0)

最近在uniapp开发时又遇到了安卓手机不兼容问题,ios系统无影响。

开发背景:小编想通过网格布局来实现答题卡的布局,实现五列多行的形式。

代码片段:

<view class="question-grid">
          <view
            v-for="(question, index) in questions"
            :key="index"
            class="grid-item"
            :class="{
              current: currentQuestionIndex === index,
              answered:
                question.type !== 2 &&
                question.userAnswer &&
                question.userAnswer === question.correctAnswer,
              wrong:
                question.type !== 2 &&
                question.userAnswer &&
                question.userAnswer !== question.correctAnswer,
              answered:
                question.type === 2 &&
                question.userAnswer &&
                question.userAnswer.length > 0 &&
                question.userAnswer === question.correctAnswer,
              wrong:
                question.type === 2 &&
                question.userAnswer &&
                question.userAnswer.length > 0 &&
                question.userAnswer !== question.correctAnswer,
            }"
            @click="jumpToQuestion(index)"
          >
            {{ index + 1 }}
          </view>
        </view>
.question-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
  height: 500rpx;
  overflow-y: scroll;
}

.grid-item {
  width: 100%;
  aspect-ratio: 1/1;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8f9fc;
  color: #555;
}

究其原因:原来安卓系统对于aspect-ratio的支持不一致,导致这个样式在安卓系统上生效。所以小编要换个样式来实现等比例缩放。可以使用padding-top替代aspect-ratio,并设置height: 0确保容器高度完全由padding控制,最终的样式代码如下:

.question-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
  height: 500rpx;
  overflow-y: scroll;
}

.grid-item {
  position: relative;
  width: 100%;
  height: 0;
  padding-top: 100%;
  justify-content: center;
  align-items: center;
  border-radius: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8f9fc;
  color: #555;
}
/* 添加内部容器 */
.grid-item-content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

这样就成功解决了aspect-ratio: 1 / 1带来的兼容性问题啦


网站公告

今日签到

点亮在社区的每一天
去签到