Home > Mobile >  Iterating with rails and using bootstrap to get cards to display in columns of 3?
Iterating with rails and using bootstrap to get cards to display in columns of 3?

Time:11-09

I am trying to get iterate through rails to create cards that grid in 3 then new line etc using each. Currently the cards only stack vertically. I would like them to be in columns of 3 and then resize to stack when the screen is made small.

Currently my code looks like this: https://i.imgur.com/mnbDIl5.png

And when I make my screen smaller it appears to go to a 3x3 like this: https://i.imgur.com/G2T9leW.png

Could anyone please help/suggest where I am going wrong?

Currently using Bootstrap v5.2.2

Thanks in advance!

<div  style="background-color:#ffa82e00;">
  <% @drinks.each do |drink| %>
      <div >
        <div  >
          <%= cl_image_tag drink.photo.key, height: 350, width: 350, crop: :fit if drink.photo.attached? %>
          <div >
            <h5 ><%= link_to drink.name, drink_path(drink) %></h5>
            <p >Price: £<%= drink.price %></p>
            <button type="button" ><%= link_to "Buy now", new_drink_order_path(drink) %></button>
          </div>
        </div>
      </div>
  <% end %>
</div>

The cards only stack 1 by 1 no matter the viewport size, and my novice knowledge of bootstrap is hindering me from getting them to display in columns of 3.

CodePudding user response:

Try this:

<div >
<% @drinks.each do |drink| %>
  <div >
      <div  style="background-color:#ffa82e00;">
        <div  >
          <%= cl_image_tag drink.photo.key, height: 350, width: 350, crop: :fit if drink.photo.attached? %>
          <div >
            <h5 ><%= link_to drink.name, drink_path(drink) %></h5>
            <p >Price: £<%= drink.price %></p>
            <button type="button" ><%= link_to "Buy now", new_drink_order_path(drink) %></button>
          </div>
        </div>  
      </div>
  </div>
<% end %>
</div>

You can wrap cards in the grid like that. This will make a grid of 3 cards wide on lg screens and above then reduces down to 1 column below that.

The loop also changed slightly to more correctly duplicate the card itself, and not extra code.

https://getbootstrap.com/docs/5.2/layout/grid/

The docs above explain the columns in a bit more detail. Version 5.2 automatically handles wrapping columns after 12 columns are exceeded, so this should be all you need!

  • Related