You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Bootstrap与NuxtJS实现响应式图片马赛克首图居中布局问题

解决方案

问题根因

  • 媒体查询漏写px单位,max-width: 576 不会生效,必须写为max-width: 576px
  • 没有给图片设置填充规则,图片无法自适应容器尺寸保持正方形
  • 外层容器没有设置统一宽高比,布局容易塌陷
  • flex子项缺少对齐属性,无法保证内容居中

修改后完整代码

<template>
  <div class="mosaic-container d-flex flex-column flex-sm-row">
    <div class="small-tiles d-flex flex-sm-column flex-row w-100">
      <img
        src="../../assets/images/image2.png"
        alt="The second image"
        class="img-fluid"
      />
      <img
        src="../../assets/images/image3.png"
        alt="The third image"
        class="img-fluid"
      />
    </div>
    <div class="center-tile w-100">
      <img
        src="../../assets/images/image1.png"
        alt="The first image"
        class="img-fluid"
      />
    </div>
    <div class="small-tiles d-flex flex-sm-column flex-row w-100">
      <img
        src="../../assets/images/image4.png"
        alt="The fourth image"
        class="img-fluid"
      />
      <img
        src="../../assets/images/image5.png"
        alt="The fifth image"
        class="img-fluid"
      />
    </div>
  </div>
</template>

<script>
export default {
}
</script>

<style lang="scss" scoped>
.mosaic-container {
  width: 100%;
  // 移动端宽高比1:2,竖排布局总高是宽的2倍
  aspect-ratio: 1/2;
  @media only screen and (min-width: 576px) {
    // 桌面端宽高比2:1,横排布局总宽是高的2倍
    aspect-ratio: 2/1;
  }
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.small-tiles {
  @media only screen and (max-width: 575px) {
    height: 25%;
  }
  @media only screen and (min-width: 576px) {
    width: 25%;
  }
}

.center-tile {
  @media only screen and (max-width: 575px) {
    height: 50%;
  }
  @media only screen and (min-width: 576px) {
    width: 50%;
  }
}
</style>

核心修改说明

  1. 替换了原断点逻辑,使用bootstrap自带的flex-sm-row类实现≥576px时横向排列,<576px时纵向排列,和媒体查询断点保持一致
  2. 新增aspect-ratio属性固定容器宽高比,避免不同设备下布局变形
  3. 给所有图片设置object-fit: cover,保证图片填充满正方形容器且不会拉伸变形
  4. 修正了媒体查询的单位错误,同时调整移动端断点为max-width:575px,避免和桌面端断点重叠
  5. 给small-tiles新增flex排列规则,桌面端内部图片竖排,移动端内部图片横排,符合布局要求

内容的提问来源于stack exchange,提问作者user237

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:09:01