Bootstrap - columns mapping (similar to row-cols-*)

Viewed 182

I have a question about Bootstrap. Is there simple solution for rendering array of elements in columns automatically, that works similar to row-cols-*?

Current code:

 <div className="row row-cols-3">
      {array.map((item) => (
        <div className="col" key={item.id}>
          <div class="card" style={{ width: "12rem", height: "12rem" }}> 
            <div class="card-body">
              {item.name} 
            </div> 
           </div>
        </div>
      ))}
 </div>

And that renders in this order: enter image description here

But I want layout to be like this: enter image description here

I tried with flex order but I can't work it out in simple way...

1 Answers

There are basically 2 options.

1 - Use flex-column and limit the height of the flexbox container (row) to roughly double the height of the columns. This is assuming you want 2 rows. If you want 3 rows you would triple the height, 4 rows quadruple the height, etc..

      <div className="row row-cols-3 flex-column" style={{ height: "26rem" }}>
              {array.map((item) => (
                <div className="col d-flex justify-content-center py-2" key={item}>
                 <div className="card" style={{ width: "12rem", height: "12rem" }}> 
                    <div className="card-body">
                      {item} 
                    </div> 
                   </div>
                </div>
              ))}
      </div>

2 - Use card-columns (Bootstrap 4 only) instead of the grid. CSS multi-column layout naturally order top to bottom instead of left to right.

       <div className="card-columns mx-auto">
              {array.map((item) => (
                <div className="card" key={item} style={{ width: "12rem", height: "12rem" }}>
                    <div className="card-body">
                      {item} 
                    </div> 
                </div>
              ))}
       </div>

Demo

Related