如何将Bootstrap卡片列表改为垂直排列而非水平排列?
实现车辆卡片垂直排列的修改方案
你的代码存在两个核心问题导致卡片水平排列:一是在{%for%}循环内重复生成了section、container和row布局容器,二是row上的row-cols-2 row-cols-md-3 row-cols-xl-4类会让卡片在不同屏幕尺寸下分成多列。按照以下步骤修改即可实现垂直排列(每行一个卡片):
修改步骤
- 将
section、container和row移到{%for%}循环外部,避免重复生成布局结构 - 修改
row的类为gx-4 gx-lg-5 row-cols-1 justify-content-center,row-cols-1会强制每行只显示一个卡片 - 保留卡片的
col mb-5类,确保卡片占满整行宽度并保持底部间距
修改后的完整代码
{% extends 'index.html' %} {% block body_block %} <section class="py-5"> <div class="container px-4 px-lg-5 mt-2"> <div class="row gx-4 gx-lg-5 row-cols-1 justify-content-center"> {% for p in carslist %} <div class="col mb-5"> <div class="card h-100"> <!-- Product image--> <img class="card-img-top" src="{{p.carpic.url}}" alt="..." /> <!-- Product details--> <div class="card-body p-4"> <div class="text-center"> <!-- Product name--> <h5 class="fw-bolder">{{p.carcompany}}</h5> <p>{{p.carmodel}}</p> <!-- Product price--> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Price: {{p.carprice}}</li> <li class="list-group-item">Kms: {{p.carkms}}</li> </ul> </div> <!-- Product actions--> <div class="card-footer p-4 pt-0 border-top-0 bg-transparent"> <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#">View Details</a></div> </div> </div> </div> {% endfor %} </div> </div> </section> {% endblock %}
内容的提问来源于stack exchange,提问作者Anwar Ahammed
相关产品推荐
相关产品推荐

