如何调整不同页面中Bootstrap卡片的间距与宽度并解决布局不生效问题
问题原因
你使用col-lg-3时justify-content不生效,是因为Bootstrap栅格系统总宽度为12,一行放4个col-lg-3的总宽度刚好是4*3=12,占满了整行空间,没有剩余空间可供对齐规则分配,所以对齐类不会产生效果。
分场景实现需求
你不需要大幅修改原有代码,仅需调整少量配置即可同时满足两个页面的需求:
1. 图书页(增大卡片宽度)
保留第6行的col-lg-3配置,做两处小调整即可:
- 把外层container的自定义宽度
style="width:70%"调大,比如改成style="width:85%",或者直接用Bootstrap原生的container-lg类适配不同屏幕的最大宽度 - 给
card-flyer加w-100类,让卡片占满整个列的宽度
如果需要调整卡片之间的间距,可以给row加gx-*(水平间距)、gy-*(垂直间距)类,*替换为1-5的数字,数值越大间距越大。
2. 着陆页(增大卡片间距)
将第6行的col-lg-3修改为col-lg-2即可,4个col-lg-2总宽度为4*2=8,剩余4份宽度会自动被justify-content-around规则分配为卡片之间的间隔,自然得到更大的间距。如果觉得间距还不够,同样可以增大row的gx-*类数值。
优化后参考代码
<section id="about" class="ts-block" > <div id="cards_landscape_wrap-2"> <!-- 图书页把width改成更大的数值,着陆页保留70%即可 --> <div class="container" style="width:70%"> <!-- row默认就是flex布局,不用额外加d-flex,gx-4是默认水平间距,可自行调整数值 --> <div class="row gx-4 gy-4 justify-content-around"> @foreach($products as $product) <!-- 着陆页把col-lg-3改成col-lg-2,图书页保留col-lg-3 --> <div class="col-xs-12 col-sm-6 col-md-3 col-lg-3"> <a href="{{route("products.show",$product->slug)}}"> <!-- 加w-100让卡片占满列宽 --> <div class="card-flyer w-100"> <div class="text-box"> <div class="image-box"> <img src="{{asset($product->image)}}" alt="{{$product->title}}" class="img-fluid rounded mx-auto d-block" width="100%"/> </div> <div class="card-footer"> <i class="text-muted"><strike>Ksh.{{$product->old_price}}</strike></i> <span class="text-primary font-weight-bold">Ksh.{{$product->price}}</span><br> <span class="mybuttonoverlap btn btn-primary">View</span> </div> </div> </div> </a> </div> @endforeach </div> </div> </div> </section>
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

