Home > other >  Is this layout possible with implicit CSS grid?
Is this layout possible with implicit CSS grid?

Time:05-26

I'm using implicit CSS grid with: grid-template-columns: 1fr 1fr;

Is it possible to make it look like a zigzag layout? Like:

<image> <text>
<text> <image>
<image> <text>
<text> <image>
<image> <text>
<text> <image>
<image> <text>
<text> <image>
...

I made a pen here: https://codepen.io/stdusan/pen/yLvPKNb

body {
  padding: 50px;
}

div {
  padding: 20px;
}

.image {
  background: red;
  padding: 20px;
}

.text {
  background: #ddd;
  padding: 20px;
}

.grid {
  display: grid;
  gap: 20px;
  grid-template-columns: 1fr 1fr;
}
<div >
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
</div>

CodePudding user response:

Yes

.image {
  background: red;
  padding: 20px;
}

.text {
  background: #ddd;
  padding: 20px;
}

.grid {
  display: grid;
  gap: 20px;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: dense; /* this */
}

.image:nth-child(4n   3) {
  grid-column: 2; /* and this */
}
<div >
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
  <div ><img src="https://picsum.photos/200/200" alt=""></div>
  <div >Some text</div>
</div>

CodePudding user response:

With CSS I don't think so, can't you just rearrange HTML so it flows like you described it,

<image/>
<text/>
<text/>
<image/>
...

and leave CSS as it is, that should get you desired results.

  • Related