Search code examples
htmlcssbootstrap-5

Bootstrap 5 Responsive Layout cards / grid / columns, how to?


I am trying to build an HTML layout similar to the image below. I can't seem to get there with Bootstrap 5, and keeping everything responsive.

Any help would be appreciated!

enter image description here

I attempted to make two columns, one for the large card.. and then have the smaller cards on the right. But the right column only stacked on top of each other, not side by side...


Solution

  • Bootstrap as a framework is good at solving most problems. However, it is not a solution for everything.

    The Bootstrap grid consists always of 12 columns. Your grid in the picture has 7 columns. 7 columns can't be fit into 12 (1,2,3,4,6 could).

    So you're left to write your own grid.

    First, you need a container and create a 7-column layout. You can do that by using this CSS:

    .container {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
    }
    

    next, you have to let the first block span multiple columns and rows which can be done by adding this to the first card:

    .first-card {
      grid-column: span 3;
      grid-row: span 2;
    }
    

    If you want to have the smaller boxes as squares like in your picture, you can simply use aspect-ratio: 1;

    /* script just for creating the elements */
    for (let i = 0; i < 23; i++) {
      let card = document.createElement('div');
      card.classList.add('card');
      card.textContent = i + 1;
      container.appendChild(card);
    }
      
    #container {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 0.5em;
      .card {
        background-color: orange;
        color: white;
        font-size: 2em;
        display: flex;
        justify-content: center;
        align-items: center;
        &:nth-child(1) {
          grid-column: span 3;
          grid-row: span 2;
        }
        &:not(:nth-child(1)) {
          aspect-ratio: 1;
        }
      }
    }
    <div id="container"></div>

    This of course can be done responsive as well. If so, you need to provide more details on how the grid should change on certain viewports.