首页 > 解决方案 > 当引导卡由 django 生成时,如何使它们彼此相邻?

问题描述

在此处输入图像描述我在 django 中做了一个博客,但是有一个问题。每当我创建一个新的博客文章时,它会向下发送引导卡,而不是在另一个引导卡旁边,这意味着它是垂直而不是水平的。

{% extends 'portfolio/base.html' %}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
    <title>{% block title %}Blog{% endblock %}</title>
</head>
<body>
{% block content %}
<div class="container text-center">
    <h2>Blogs</h2>
    <h2>PyPatriot has posted {{ blogs.count }} Blog{{ blogs.count | pluralize }}</h2>

    <div class="row">
        <div class="col-sm-6">
            {% for blog in blogs %}
                <div class="card" style="width: 18rem;">
                <img src="{{ blog.cover_photo.url }}" class="card-img-top" width="230" height="230">
                <div class="card-body">
                    <h4 class="card-title">{{ blog.title }}</h4>
                    <h6>{{ blog.date | date:'M d Y'}}</h6>
                    <p class="card-text">{{ blog.description | truncatechars:70 }}</p>
                    <a href="{% url 'blog:detail' blog.id %}" class="btn btn-primary">View</a>
                </div>

            {% endfor %}
        </div>
    </div>


{% endblock %}
</body>
</html>

看看它对我从 django admin 添加的博客文章做了什么

标签: htmlcssdjangobootstrap-4jinja2

解决方案


首先你不需要这个: <div class="col-sm-6"> 因为它把你所有的卡片都塞进了一个半屏幕宽度的列中。

接下来,引导卡片像普通<div>元素一样堆叠。要使它们并排运行,您必须通过构建自己的布局(例如使用@ImustAdmit 的解决方案、flexbox 或其他方法)或使用 Bootstraps 的.card-columns类(请参阅此处)来使它们并排。在您的情况下,只需将 a 包裹<div class="card-column">在您的循环中。

要更改不同断点的布局,您可以使用类似

.card-columns {
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
}

(这直接来自 Bootstrap 卡页面)。

您还可以使用Isotope.js等 3rd 方库来获得更精美的布局,或者使用 flexbox 获得更多 DIY 解决方案。基本上将卡片视为普通 div,或使用 Bootstrap 辅助类。


推荐阅读