Search code examples
htmltwitter-bootstrapbootstrap-4django-templatesjinja2

List 3 bootstrap cards per row using template loop


I'd like to list the cards as down below:

enter image description here

This is the code so far. My cards are listed one by one vertically. How can I achieve this?

{% extends 'base_content.html' %}
{% block content %}
{% for item in CATEGORY_CHOICES %}
<div class="row" style="justify-content: center;">
<div class="col-sm-3">
  <div class="card">
    <div class="card-body">
      <h5 class="card-title">{{ item.1 }}</h5>
      </div>
    </div>
  </div>
</div>
{% endfor %}
{% endblock %}

Solution

    1. The loop currently creates a new row for each item, which is why every card is stacking. It should only loop col, not row.

    2. col-sm-3 means "use 3/12 space per column at sm and above" which means 4 columns (not 3) at the sm breakpoint and above. Use col-sm-4 to display 3 cards per row at sm and above, or just col-4 if you want 3 cards per row at all times.

    {% extends 'base_content.html' %}
    {% block content %}
    
    <!-- don't loop here -->
    <div class="row justify-content-center">
    
      <!-- only loop the columns -->
      {% for item in CATEGORY_CHOICES %}
      <div class="col-sm-4"> <!-- not "col-sm-3" -->
        <div class="card">
          <div class="card-body">
            <h5 class="card-title">{{ item.1 }}</h5>
          </div>
        </div>
      </div>
      {% endfor %}
    
    </div>
    
    {% endblock %}