Reputation: 2741
Is there a way with CSS, to kinda "interweave" elements?
Say I have react that generates a list of images, and a list of text.
The html would look like
<div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<img src="image1.jpg" />
<img src="image2.jpg" />
<img src="image3.jpg" />
<img src="image4.jpg" />
<img src="image5.jpg" />
</div>
And I wanted them displayed like this
<div>
<p>Paragraph 1</p>
<img src="image1.jpg" />
<p>Paragraph 2</p>
<img src="image2.jpg" />
<img src="image3.jpg" />
<p>Paragraph 3</p>
<img src="image4.jpg" />
<p>Paragraph 4</p>
<img src="image5.jpg" />
<p>Paragraph 5</p>
</div>
I feel like it can easily be done in a React component, but I"m wondering if there's a way of doing this with either CSS grid or flex.
Upvotes: 0
Views: 137
Reputation: 96
You can do this with the order property of grid elements.
The following code should do the trick:
div { display: grid; }
p:nth-child(1) { order: 1; }
p:nth-child(2) { order: 3; }
p:nth-child(3) { order: 6; }
p:nth-child(4) { order: 8; }
p:nth-child(5) { order: 10; }
img:nth-child(6) { order: 2; }
img:nth-child(7) { order: 4; }
img:nth-child(8) { order: 5; }
img:nth-child(9) { order: 7; }
img:nth-child(10) { order: 9; }
<div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
<img src="image1.jpg" />
<img src="image2.jpg" />
<img src="image3.jpg" />
<img src="image4.jpg" />
<img src="image5.jpg" />
</div>
By default all grid items have an order value of 0 and the lower the order value is the higher the grid item appears. I suggest you use different selectors for the elements (add classes to them).
Upvotes: 2