You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让博客新增帖子横向并排展示而非纵向堆叠?

解决博客帖子卡片横向并排问题

你的代码存在几个关键问题,导致卡片始终纵向堆叠:

  • 循环内重复生成<head>、<body>标签,违反HTML结构规范——整个页面只能有一组<head>和<body>,这类标签应放在父模板base.html中,不能在帖子循环里重复输出。
  • 每个帖子单独使用card-deck容器,card-deck是用于容纳多个卡片的容器,而非单个卡片的包裹层;同时给card添加row类也是错误的,row是Bootstrap的栅格行容器,不该用在卡片上。

修正方案(用Bootstrap栅格系统实现横向排列)

移除错误的结构标签,改用栅格系统控制卡片布局,实现响应式横向排列:

{% extends "online_shop/base.html" %}
{% load static %}
{% block content %}
<!-- 外层栅格行,承载所有帖子卡片 -->
<div class="row mt-4">
    {% for post in posts %}
        <!-- 响应式列配置:中等屏幕每行3张,小屏幕每行2张,超小屏幕每行1张 -->
        <div class="col-md-4 col-sm-6 mb-4">
            <div class="card h-100">
                <img class="card-img-top" src="{% static 'online_shop/unicorn-cake-14.jpg'%}" alt="Card image cap" style="height: 310px; object-fit: cover;">
                <div class="card-body">
                    <h2 class="h5"><a class="article-title text-decoration-none" href="#">{{ post.title }}</a></h2>
                    <p class="card-text">{{ post.content|truncatewords_html:15 }}</p>
                </div>
                <div class="card-footer">
                    <small class="text-muted"><a href="#" class="text-muted text-decoration-none">{{ post.author }}</a></small>
                    <small class="text-muted ms-2">{{ post.date_posted|date:"F d, Y" }}</small>
                </div>
            </div>
        </div>
    {% endfor %}
</div>
{% endblock content %}

补充说明

  • 用mt-4替代空div实现顶部间距,符合Bootstrap类规范;
  • h-100让所有卡片高度一致,避免布局参差不齐;
  • object-fit: cover确保图片按比例填充容器,不会拉伸变形;
  • col-md-4 col-sm-6实现响应式适配,不同屏幕尺寸自动调整每行卡片数量。

内容的提问来源于stack exchange,提问作者Rin Hyakuya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 10:51:32