5

I want to mimic this pattern (over and over):

enter image description here

So I wrote grid-template-columns: 65% 35% for the first row. Yet, I want to do grid-template-columns: 65% 35% for a second row (and the fourth, and the sixth and so on), but I'm not sure how can I do that while maintaining 65% and 35%.

#parent {
  display: grid;
  grid-template-columns: 60% 40%;
  grid-gap: 24px;
}

.child {
  height: 50px;
  background-color: #DDD;
}
<div id="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

2 Answers 2

4

You can rely on nth-child selector to do this. Note how the pattern is repeating each 4 elements.

#parent {
  display: grid;
  grid-template-columns: 35% 1fr 35%;
  grid-gap: 24px;
}

.child {
  height: 150px;
  background-color: #DDD;
}
.child:nth-child(4n+1),
.child:nth-child(4n+4){
  grid-column:span 2;
}
<div id="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div

You can also do the same consider only fr unit. The result won't be exactly the same fr and % aren't resolved the same way.

#parent {
  display: grid;
  grid-template-columns: 3.5fr 3fr 3.5fr;  /* 3.5 + 3.5 + 3 = 10*/
  grid-gap: 24px;
}

.child {
  height: 150px;
  background-color: #DDD;
}
.child:nth-child(4n+1),
.child:nth-child(4n+4){
  grid-column:span 2;
}
<div id="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div

Sign up to request clarification or add additional context in comments.

Comments

2

You can achieve this by creating a three-column grid with grid-template-columns: repeat(3, 33.333%); and adding an additional class for the children that will stretch the element into two columns grid-column: span 2;

Result:

https://codepen.io/hisbvdis/pen/vYBaZQb

#parent {
  display: grid;
  grid-template-columns: repeat(3, 33.333%);
  grid-gap: 24px;
}

.child {
  height: 150px;
  background-color: #DDD;
}

.wide {
  grid-column: span 2;
}
<div id="parent">
  <div class="child wide"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child wide"></div>
  <div class="child wide"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child wide"></div>
  </div

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.