本文介绍如何使用 CSS Flexbox 将 Django 博客中的文章卡片从默认的垂直堆叠改为响应式横向并排展示,解决 .card 元素逐个换行的问题,并兼顾移动端适配与视觉一致性。
本文介绍如何使用 css flexbox 将 django 博客中的文章卡片从默认的垂直堆叠改为响应式横向并排展示,解决 `.card` 元素逐个换行的问题,并兼顾移动端适配与视觉一致性。
在当前的 post.html 模板中,每个
✅ 正确做法:重构 HTML 结构 + 添加 Flex 样式
首先,删除模板中循环内重复的 、 及多余 然后,在你的 CSS 文件(如 base.css 或 {% static %} 引入的样式表)中添加以下响应式 Flex 规则: 通过这一改造,你无需依赖 Bootstrap 的 card-deck(已废弃)或浮动 hack,即可获得现代、健壮、易维护的网格布局。{% extends "online_shop/base.html" %}
{% load static %}
{% block content %}
<!-- ✅ 外层唯一容器:启用 Flex 布局 -->
<div class="blog-grid">
{% for post in posts %}
<div class="post-card">
<img class="card-img-top" src="%7B%%20static%20'online_shop/unicorn-cake-14.jpg'%20%%7D" alt="{{ post.title }}" style="max-width:90%" style="max-width:90%"><div class="card-body">
<h2><a class="article-title" 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="#">{{ post.author }}</a></small>
<small class="text-muted" style="margin-left: 5px;">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
/* 博客卡片容器:水平排列 + 自动换行 */
.blog-grid {
display: flex;
flex-wrap: wrap;
justify-content: center; /* 居中对齐整行卡片 */
gap: 24px; /* 卡片间统一间距(推荐替代 margin)*/
padding: 20px;
}
/* 单张卡片:固定宽度 + 响应式约束 */
.post-card {
flex: 0 1 300px; /* 不放大、可缩小、基础宽度 300px */
max-width: 300px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.08);
background: white;
overflow: hidden;
}
/* 移动端优化:单列显示 */
@media (max-width: 768px) {
.blog-grid {
justify-content: flex-start;
}
.post-card {
flex: 0 1 100%;
max-width: 100%;
}
}
⚠️ 关键注意事项
✅ 最终效果











