0

I'm trying to figure out the best way to achieve this grid layout. Naturally, it has to be responsive so the layout changes and goes through 3 states, from large to medium to small screens. I have attached an image of what I'm trying to get. I am using Bootstrap so have access to their grid feature but I'm not sure if this might be too complicated for that

Would a layout like this be better suited to a JS plugin (masonry or alike) or would flexbox or CSS grid be able to achive something like this?

enter image description here

Adam
  • 303
  • 4
  • 16
  • Check this answer out, it is something similar to what you're trying to achieve. https://stackoverflow.com/a/39175839/10831896 – ajmnz Sep 14 '20 at 14:20
  • I don't know Bootstrap, but this can perfectly be made with flexbox in combination with media queries... – GreyRoofPigeon Sep 14 '20 at 14:37

1 Answers1

0

This is a classic scenario for just plain CSS Grids. Below you have a super simple implementation of this (note: there are better ways to do this, more implicit and shorthanded versions that don't even require some of the breakpoints, but this is the more clear way to understand what's going on imo).

I recommend reading this article for full description of the CSS Grids spec: https://css-tricks.com/snippets/css/complete-guide-grid/

Here is a Codepen with the working solution: https://codepen.io/sergiofruto/pen/zYqaLEL

HTML

<div class="grid">
    <div class="grid-item">1</div>
    <div class="grid-item">2</div>
    <div class="grid-item">3</div>
    <div class="grid-item">4</div>
    <div class="grid-item">5</div>
</div>

CSS

.grid {
  display: grid;
  grid-gap: 10px;
  width: 100%;
  /*no  explicit height, let the children determine it */
}

.grid-item {
  /*arbitrary height, could be less, more, or grow depending on the content */
  height: 200px;
  font-size: 32px;
  color: white;
  background-color: black;
  text-align: center;
  border: 2px solid white;
}

@media (min-width: 768px) {
  .grid {
    /* here we set the two column layout fr are special units for grids, it represents the available space */
    grid-template-columns: 1fr 1fr;
  }
}

@media (min-width: 1024px) {
  .grid {
    height: 400px;
    /* here we set the four column layout, fr are special units for grids, it represents the available space */
    grid-template-columns: 1fr 1fr 1fr 1fr;
    /* here we set the two row layout, fr are special units for grids, it represents the available space */
    grid-template-rows: 1fr 1fr;
  }

  .grid-item {
    height: auto;
  }

  .grid-item:first-child {
    /* here we set a special size for the first children of the grid */
    grid-column: 1 / 3;
    grid-row: 1 / 3;
  }
}