Bootstrap图片行移动端无法正常折叠,如何消除空白区域?
问题描述
使用Bootstrap制作图片行布局,需求为:手机屏幕每行显示2张图片,所有大于手机尺寸的屏幕每行显示3张图片。下方代码在大屏设备上运行正常,但在手机端第三张图片后会出现空白区域,需解决该移动端空白问题。
原代码:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <div class="row no-gutters"> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> </div> <div class="row no-gutters"> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> </div>
问题原因
你把每3张图片放在独立的.row容器里,在移动端(col-6占50%宽度),单个.row里的3个col-6会自动排成两行:前两个占满一行,第三个单独占一行的50%,剩下50%就会出现空白。下一个.row的图片又会从新行开始,导致视觉上第三张图片下方有空白区域。
解决方案
将所有图片放入同一个.row容器中,利用Bootstrap栅格系统的自动换行特性,移动端会自动按每行2张排列,大屏按每行3张排列,不会出现空白。
修正后的代码:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <div class="row no-gutters"> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> <div class="col-6 col-sm-4"> <img src="https://via.placeholder.com/600" style="max-width: 100%;"> </div> </div>
内容的提问来源于stack exchange,提问作者Philip7899
相关产品推荐
相关产品推荐

