Restricting the number of blocks in each row using Django and Bootstrap

I'm working on a webpage where each item is represented by a bootstrap card. In my template, I use a loop to create cards for each item. However, I'm facing an issue - how can I restrict the number of cards displayed in a single row before moving on to the next one?

 <div class = 'card-group'>
{% for plant in plant%}
{% if plant.available%}
<div class="card text-white bg-dark mb-3" style=''>
  <img style='height: auto; max-width: 100%;' src="{{plant.thumbnail}}" alt="...">
  <div class="container">
    <h4 style='color:white;' class="card-title"><b>{{plant.name |title}}</b></h4>
    <p style='font-size: 20px'>Soil: {{plant.soil |title}}</p>
    <p style='font-size: 20px'>Price per unit: £{{plant.price |title}}</p>
  </div>
  <div class='button-section'>
  <button class="order-button"><a href=''>Order Online</a></button>
  </div>
</div>

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

The current CSS styling for the cards is as follows:

.card {
    margin: 10px;
    display: flex;
}

.card-group {
    justify-content: space-evenly;
}

(card title styles...)

.card-body {
    text-align: left;
}

(card button styles...)

My goal is to have only four items displayed per row, and then move on to the next row with the rest of the items. Any suggestions on how to achieve this layout?

Answer №1

In Bootstrap, each row is made up of 12 columns in total. For example, if your container is set to col-4, the div will print out 3 columns per row since 4x3 equals 12. On the other hand, setting it to col-2 would result in 6 smaller divs per row as 2x6 also equals 12.

Answer №2

To achieve this layout, you can utilize the forloop.counter and divisibleby template tags in your code. Here's an example implementation:

{% for item in items %}

  {% if forloop.counter0|divisibleby:"4" %}
    <div class="row">
  {% endif %}

  {% if forloop.counter0|divisibleby:"4" %}
    </div>
  {% endif %}

{% endfor %}

Alternatively, you can handle this logic within your views using the following approach:

rows = []
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]  # Assume these are retrieved from Item.objects.all() etc.
per_row = 4

i = 0
while True:
    row_items = items[i * per_row : (i + 1) * per_row]
    if not row_items:
        break
    rows.append(row_items)
    i += 1
print(rows)

After running the provided code snippet, the output will be

[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
. This results in nested lists, requiring two for loops in the template to iterate through.

Answer №3

It worked like a charm

<section class="row row-cols-2 row-cols-lg-6 g-3">

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

Tips for utilizing external CSS solely within a designated section

Currently, I'm working on a web application that requires the option to display a specific area using Bootstrap 4.1 or Bootstrap 3. The entire application is already built using Bootstrap 3: https://i.sstatic.net/pPuM6.png I have already implemented ...

Repositioning with Flexbox: shifting the middle element to a new line

I have a flex item that contains three divs. ┌────────────────────────────────────────┐ | WRAPPER | | ┌─────────┬─ ...

`Gradient blending in ChartJS`

Currently, I am facing an issue with my line chart having 2 datasets filled with gradients that overlap, causing a significant color change in the 'bottom' dataset. Check out my Codepen for reference: https://codepen.io/SimeriaIonut/pen/ydjdLz ...

Is it possible to add padding to an HTML element without affecting its overall dimensions?

Is it possible to apply padding to a div without increasing its size? <div id="someDiv"> someContent </div> #someDiv{ padding: 1em; } One potential solution is to add another nested div within #someDiv and apply margin to that, rathe ...

What is the best way to vertically align an InputLabel within a MUI Grid item?

I'm trying to vertically center the InputLabel inside a MUI Grid item. Here's what I've attempted: import { FormControl, Grid, Input, InputLabel, TextField } from "@mui/material"; export default function App() ...

Easily toggle between different content within the same space using Twitter Bootstrap Tabs feature. Display the tabs

I made a modification to the bootstrab.js file by changing 'click' to 'hover': $(function () { $('body').on('hover.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.p ...

Using Docker Compose for both production and development environments

Currently, I use Python with Django, but the language is not crucial to this question. When I write my code, I typically execute the following command: ./manage.py runserver This command sets up the webserver, handles static files, and enables automatic ...

Adding a special ie7 glow effect to hyperlinks

Currently, I am facing an issue with a website that I am in the process of redesigning. The problem seems to be specific to Internet Explorer 7 (ie7). If you visit dev.indigoniche.com (you may be redirected back to the main site due to a cookie issue, in w ...

Enhance the functionality of your website by implementing a zoom feature

I am looking to dynamically change the CSS of a div using jQuery when it is clicked. The challenge I am facing is that there are multiple divs with the same class and I am unable to modify their classes as they are created dynamically using PHP. <div ...

Struggling with Django relationships?

I am facing an issue with the data in my models and template. Here is an example of what I have: class Companies(models.Model): ComName = models.CharField(max_length=255) ComURL = models.CharField(max_length=1024,null=True) class Products(mod ...

The specified 'image' identifier has not been defined. There is no such member within 'never'

Edit :: Finally, I managed to get the output successfully, but there's still an error that baffles me. https://i.stack.imgur.com/2wrNM.pngAlthough I've tackled similar issues in the past, this particular one seems elusive. I attempted using "?", ...

Column div being obscured by footer

My footer is causing overlap issues with the div above it on my mobile website. Here's a visual representation: Current view on my phone: https://i.stack.imgur.com/RpvWM.png Desired view: https://i.stack.imgur.com/KHVcm.png The code for the are ...

Encircle a particular row in a table with a border

I'm having trouble creating a border around only the top row of my table. Right now, the border is only displayed around the outside of the entire table. I also want to add a border specifically to the first row that contains 'Team, Correct Picks ...

What is the process for calling a class in HTML from a <Div> tag?

I am struggling with the following code snippet: <p class=‘majed’ style="color:#FF0000";>Red paragraph text</p> How can I reference the 'majed' class above? <Div class=‘majed’ > </Div> Your help is greatly appr ...

Using the Jquery validation plugin for Internet Explorer 9 when the website first loads

Our website is currently using Jquery v1.9.0 and jquery validation plugin v1.10.0. The form on our site consists of two text boxes and a submit button. When the submit button is clicked, the input elements are validated and a JavaScript function is trigger ...

Using PHP, HTML, and JavaScript to generate a dropdown list from a database

I am looking to create a dynamic dropdown list populated from a database using JavaScript. My goal is to design a form where users can add multiple rows by clicking the "add more" button. The form will include both a text input field and a dropdown list. ...

Does the downloading of images get affected when the CSS file has the disabled attribute?

Is it possible to delay the download of images on a website by setting the stylesheet to 'disabled'? For example: <link id="imagesCSS" rel="stylesheet" type="text/css" href="images.css" disabled> My idea is to enable the link later to tri ...

The integration of Angular CLI with SCSS is no longer a separate process -

It seems like I might be overlooking something very straightforward here. After a fresh installation of angular-cli, I created a new website with SCSS. I input the SCSS in the global style.scss as well as some in a component SCSS file. However, when I se ...

Moving a button to the right side in HTML/CSS without creating any gaps

Currently, I'm working on developing a simple idle browser game. I'm facing a challenge in positioning a button on the right-middle of the box. I attempted using position: relative along with adjusting the bottom and left parameters, but I still ...

The parser for PHP CSS struggles with interpreting semicolons within property values

I encountered an issue while using a function to parse CSS files. The problem arises when the property values contain semicolons, causing it to break. Here's an example snippet from the CSS file: #logo { background-image: url("data:image/png;base ...