tomeraz
tomeraz

Reputation: 323

Responsive zig zag layout using css?

I want to create a responsive snake/zigzag layout, like so: zig zag layout starting from the middle It's a path of square images and circles starting in the center of the container and going downwards.

Number of elements is unknown and is determined by server data.

How do I achieve this using pure css?

Here's a possible code:

<div class="container">
  <div class="square"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="square"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="circle"></div>
  <div class="square"></div>
/<div>

Full Codepen

Upvotes: 2

Views: 1750

Answers (1)

Ale
Ale

Reputation: 2023

I have worked out an extremely complex hack (codepen). You really don't want this in production, though. It also only works for three “hops” (i. e. the stream of elements goes from left to right, bounces, goes back to left, bounces again and goes to eternal void, never to be seen again).

The hack works as follows: first, we calculate the position from left that we need to move our element to, for each possible “hop”. For the first hop, it's $i * 50px ($i being the 0-based index of element), for the second it's 100vw - ($i * 50px - 100vw) == 200vw - $i * 50px (100vw is window width; $i * 50px - 100vw is position of the element relative to the right screen border), and the third is $i * 50px - 200vw.

We now need to calculate max(min($first, $second), $third). Unfortunately, CSS calc() function doesn't allow that, so instead we place a special element before the figure:

.spacer {
  display: inline-block;
  max-width: 50px; /* first */
  min-width: 500px; /* third */
}

.spacer > span {
  display: inline-block;
  max-width: 300px; /* second */
  width: 10000px;
}

(You can play with this spacer thing in a separate codepen.)

Again, this is an extremely complex and slow solution, so you'd better stick with JavaScript for now (unless somebody invents some more clever CSS-only thing that would actually work).

Upvotes: 1

Related Questions