基于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>
核心修改说明
- 替换了原断点逻辑,使用bootstrap自带的
flex-sm-row类实现≥576px时横向排列,<576px时纵向排列,和媒体查询断点保持一致 - 新增
aspect-ratio属性固定容器宽高比,避免不同设备下布局变形 - 给所有图片设置
object-fit: cover,保证图片填充满正方形容器且不会拉伸变形 - 修正了媒体查询的单位错误,同时调整移动端断点为max-width:575px,避免和桌面端断点重叠
- 给small-tiles新增flex排列规则,桌面端内部图片竖排,移动端内部图片横排,符合布局要求
内容的提问来源于stack exchange,提问作者user237
相关产品推荐
相关产品推荐

