简化版的 Flexbox 方案,只用核心几行 CSS 就能限定一行产品个数
没问题!给你简化版的 Flexbox 方案,只用核心几行 CSS 就能限定一行产品个数,兼顾简洁和实用,适配你的产品卡片场景:
极简版:一行固定显示N个(以4个为例)
步骤1:HTML(保留你的结构,只加一个外层容器)
<!-- 只加这一个外层 Flex 容器,其他不变 -->
<div class="product-row">
{% for product in products %}
<div class="col">
<div class="card product-card h-100">
<!-- 你的卡片内容(图片、名称、按钮)完全不变 -->
{% if product.images.exists %}
<img src="{{ product.images.first.image.url }}" class="card-img-top product-image" alt="{{ product.images.first.alt_text|default:product.name }}">
{% else %}
<img src="https://picsum.photos/400/200?random={{ product.id }}" class="card-img-top product-image" alt="{{ product.name }}">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<a href="{% url 'product_detail' product.pk %}" class="btn btn-outline-primary">{% trans 'View Details' %}</a>
</div>
</div>
</div>
{% empty %}
<div class="col-12">
<div class="alert alert-info text-center" role="alert">
{% trans 'No products available in this category.' %}
</div>
</div>
{% endfor %}
</div>步骤2:CSS(仅5行核心代码,限定一行4个)
/* 外层Flex容器:开启换行 + 间距 */
.product-row {
display: flex;
flex-wrap: wrap; /* 超出自动换行 */
gap: 20px; /* 卡片之间的间距,调数字即可 */
}
/* 每个产品卡片:一行4个 → 宽度25%,减去间距 */
.product-row .col {
width: calc(25% - 15px); /* 核心:25%=1行4个,15px是间距均分 */
box-sizing: border-box; /* 防止padding撑宽卡片 */
}
/* 可选:手机端一行1个,仅加这1行 */
@media (max-width: 768px) {
.product-row .col { width: 100%; }
}关键简化点(不用记复杂公式)
改个数只需改2处:
- 一行3个 → 把
25%改成33.33%,15px改成13px; - 一行2个 → 把
25%改成50%,15px改成10px; - 一行1个 → 直接写
width: 100%;(手机端已适配)。
- 一行3个 → 把
- 不用管Flex复杂属性:只记
display: flex+flex-wrap: wrap+width: 百分比这3个核心。 - 保留你原有的卡片样式:
h-100继续用,保证卡片高度统一,其他样式完全不变。
效果说明
- 大屏:一行精准显示4个产品,间距均匀,卡片高度一致;
- 手机:自动变成一行1个,不用额外调整;
- 点击图片/名称跳转、卡片样式都不受影响。
超简易替代方案(直接用Bootstrap栅格,零额外CSS)
如果连CSS都不想写,直接用Bootstrap自带的列类,一行个数由列数决定(Bootstrap一行总列数是12):
<!-- 一行4个:col-lg-3(12/3=4),平板一行2个:col-md-6,手机一行1个:col-12 -->
{% for product in products %}
<div class="col-12 col-md-6 col-lg-3 mb-4"> <!-- mb-4是间距,替代gap -->
<div class="card product-card h-100">
<!-- 你的卡片内容不变 -->
</div>
</div>
{% endfor %}✅ 这个方案零CSS,只用Bootstrap原生类:
col-lg-3:大屏一行4个;col-md-6:平板一行2个;col-12:手机一行1个;mb-4:给卡片加底部间距,避免挤在一起。
这两个方案选一个就行,都是极简版,不用记复杂的Flex属性,完全适配你的原有代码!
(豆包)