2

I’m trying to create a CSS grid layout for blog posts inside a query loop. Each box should maintain an approximate 3:2 aspect ratio, and the layout needs to be dynamic. Below is what I’ve tried so far:

HTML structure cannot be changed

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

.item {
  border: 1px solid black;
  background-color: green;
  margin: 2px;
}

.item:first-of-type,
.item:nth-child(5n),
.item:nth-child(7n) {
  grid-column: span 2;
  grid-row: span 2;
}
<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <!-- More items will be added dynamically in the query loop -->
</div>

While this works for the first few items, the layout becomes inconsistent and doesn’t look good as more items are added.

Here’s the image of the layout I’m trying to achieve for reference.

css grid

How can I create a dynamic and consistent grid layout like this while keeping the aspect ratio for all items?

2
  • Looks like you could use Masonry for that but there are many examples here at SO Commented Nov 30, 2024 at 6:51
  • a good reading: css-tricks.com/… (especially the last section) Commented Nov 30, 2024 at 7:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.