What is the best way to ensure that bootstrap cards are displayed next to each other when they are dynamically created by Django?

https://i.sstatic.net/KMrO1.pngI have encountered an issue with my Django blog. When I add a new blog post, it appears below the previous posts instead of alongside them, causing a vertical layout rather than a horizontal one.

{% 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>

https://i.sstatic.net/qWjCl.png

Answer №1

First and foremost, you can eliminate the need for <div class="col-sm-6">, which condenses all your cards into a single column taking up half of the screen width.

In Bootstrap, cards are stacked like regular <div> elements by default. If you want them to display side by side, you have a few options: customize your layout using solutions like @ImustAdmit's suggestion, flexbox, or Bootstrap's predefined .card-columns class (refer to the documentation here). In your scenario, simply wrap your loop with a <div class="card-column">.

To adjust the layout for different screen sizes, you can utilize code like:

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

(taken directly from the Bootstrap card page).

You also have the option to explore third-party libraries such as Isotope.js for more intricate layouts, or employ flexbox for a hands-on approach. Essentially, treat cards like standard divs or leverage Bootstrap's utility classes.

Answer №2

To keep track of cards, remember to utilize forloop.counter

This code snippet is a segment of my website's functionality

{% for post in object_list %}
{% if forloop.counter0|divisibleby:3 %} <div class="row"> {%  endif %}
  <div class="col-md-4">
    <div class="card article">
      <a href="{{ post.get_absolute_url }}"><img class="responsive opacity" src="{{ post.img_url }}" alt=""></a> 
        <div class="card-content">
          <p class="date-field">{{ post.created_on|date:"d.m.y" }} / {{post.field}}</p>
            <h2 class="article-title"><a class="link-article" href="{{ post.get_absolute_url }}">{{ post.title }}</a></h2>
          <div class="content">
            {{ post.content|safe|truncatewords:35 }}
          </div>
          <div class="button-wrapper"><a href="{{ post.get_absolute_url }}"><button class="button button1" >Read More</button></a></div>
        </div>
    </div>
  </div>
{%  if forloop.counter|divisibleby:3 or forloop.last %}</div><br>{%  endif %}
{%  endfor %}

This setup will display 3 cards side by side in each row.

If you wish to adjust the number of cards per row, modify the value of divisibleby in

if forloop.counter0|divisibleby:3
and the columns in <div class="col-md-4">

In your specific scenario, it would appear as follows:

<div class="container text-center">
    <h2>Blogs</h2>
    <h2>PyPatriot has posted {{ blogs.count }} Blog{{ blogs.count | pluralize }}</h2>
{% for blog in blogs %}
{% if forloop.counter0|divisibleby:3 %} <div class="row"> {%  endif %}
    <div class="col-sm-4">
            <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>
    </div>
{%  if forloop.counter|divisibleby:3 or forloop.last %}</div><br>{%  endif %}
{%  endfor %}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to navigate to a specific tab in Laravel with Bootstrap version 4

I have been attempting to use Laravel and Bootstrap v4 to redirect the user back to the same tab they were previously in. For instance, if a user creates a treatment from the treatments tab, I want them to be redirected back to that "treatments" tab. Bel ...

Executing JavaScript code does not execute CSS code

Having some trouble with my Javascript and CSS. The script is functioning well, but when I use the filtering function, the CSS stops working and only the filtered results are displayed on the HTML page. Looking for advice on how to fix the Javascript. & ...

Retrieve the 'computed' CSS for the entire webpage

We operate multiple websites, each referencing 3-5 CSS files. Some of these files are shared across sites while others are specific to certain pages. Our aim is to streamline the CSS structure by consolidating into fewer files without altering the end res ...

Switch up the functionality of Bootstrap tooltips: show all the content and only hide it when hovered over

I have a page containing multiple tooltips that I would like to show all at once. All of the tooltips share a class called "tooltipWarn." <span class='warning tooltipWarn'>test</span> Using JQuery: $('.tooltipWarn').toolti ...

Calculating the Distance Between Elements within a Flex Container Using JavaScript

I am looking to calculate the margin left and right for children of a flex item <div class="sec images" style="display:flex;justify-content:space-between"> <img src="images/en_mb-mega-01.png" alt=""> ...

Utilize generated styling data bindings when referencing assets

Currently, I am working with vue-cli 3 and trying to create background-image paths. To achieve this, I am utilizing the style data bind within a v-for-loop. Below is the component structure: <template> <ul> <li v-for="(tool, inde ...

Guide to highlighting input field text using Angular

I've set up an angular page that includes an input field within its template. My goal is to highlight the text in the input field when a specific function is triggered. When I refer to "highlighting the text," I mean (check out the image below) https ...

Enhanced Custom Code Highlighting for Aptana Studio 3 with support for .less files

Looking to enhance syntax highlighting for .less files in Aptana Studio 3 but struggling to find a solution. XText only works with Eclipse, and the forums offer limited guidance. Has anyone successfully implemented custom syntax highlighting for .less fi ...

Styling a nested scrollbar using JQuery

I am looking to customize two scrollbars using a jquery plugin or JS library. Here is the HTML code: <div id="container"> <div class="fixedHeightContainer"> <div class="fixedHeightContent"> Lorem ipsum dolor sit amet, con ...

Strategies for quickly landing in top Google search results

I run a website for classified ads... Whenever users post a new ad, it gets automatically included in our dynamic sitemap (xml). Our sitemaps were submitted to Google via Webmaster Tools about two months ago. While some of the ads are indexed, it is tak ...

Determine the total number of active links on an HTML webpage using F#

Currently, I am working on developing a basic F# function that will be able to count the total number of links present in a given HTML website URL. I understand that this can potentially be achieved by counting the occurrences of the "<a" substrings, b ...

What could be causing the issue of nth-child blocking the functionality of a:hover styles?

I have a unique collection of images that are styled to resemble polaroid pictures. Each image is given a slight rotation. a.polaroid { transform: rotate(-2deg); } On hover, a scale transformation is applied. a.polaroid:hover { transform: scale(1 ...

Tips for using jQuery to slowly change a CSS property to "auto"

I've encountered a situation where I have an element styled with position:fixed, and bottom: auto;. When I apply the command .animate({bottom : '10%'});, it smoothly slides to the specified position. However, when I try to set it back to its ...

Iterating through children of the target element using the .each() method in jQuery

Currently, I am looping through the elements and extracting the src attribute from the child element. This is the snippet of HTML code that I am working with: <noscript data-alt="super awesome"> <img src="http://farm9.staticflickr.com/8235/85 ...

Several pictures are not displaying in the viewpage

I have a controller method set up to fetch files from a specific folder. public JsonResult filesinfolder(ProductEdit model) { string productid = "01"; string salesFTPPath = "C:/Users/user/Documents/Visual Studio 2015/Projects/root ...

Using a form generated on the fly for submission

Recently, I created a dynamic form that consists of select options and input boxes. Upon submitting the form, I require all data from the selects and inputs to be stored in separate variables. The following is an excerpt from the code: HTML CODE : < ...

Is it feasible to achieve a full 100% screen width within a confined div using relative positioning?

Can a div expand to 100vw within a parent div that is relative and has a limited width, without losing its height in the document like it would if positioned absolute? Is it achievable with pure CSS or do I need some jQuery or JS? body { background: ...

Is there a way to prevent Angular Material Buttons from overlapping a sticky bar when scrolling?

In my Angular application, I have a navigation bar at the top that sticks in place (position: sticky; top: 0;). Beneath the navigation bar is the content, which includes Angular material components such as mat-buttons or mat-cards. The issue arises when ...

Minimizing the length of URL query strings in Django

I've been using Django Forms for a while, but recently I encountered a challenge when creating a form with a MultipleChoiceField for data search. In order to share the URL between users, the form sends a GET request to the server to store the search p ...

Why is IE6 adding an additional margin of 50px? My code seems to be causing this issue

Currently I am working on creating a custom IE6 CSS. However, I am facing an issue where an extra 50px is being added to the header div. Even though I have set the header size to 109px, it is displaying at 159px. When I add any element below the header div ...