Using math to change a CSS class every X items in the loop?

Hi there, I want to implement a pure CSS masonry gallery, but this requires modifying a class every 11 items in the loop.

The first 11 items must have a 0:

  <li style="--n: 0;">
    <figure>
       <img...>
    </figure>
  </li>

And the next 11 items must have a 1 and so on:

  <li style="--n: 1;">
    <figure>
       <img...>
    </figure>
  </li>

I have read the docs and some related posts, but none seem to achieve precisely what I need, and I’m no good at maths.

My test loop is below, but the output is not even close to what I need.

<Loop acf_gallery="some_gallery">
    <figure>
        <a href="{Field url size=large}">
            <img src="{Field url size=medium}" />
        </a>
    </figure>
    <If check="{Math}{Get loop=count}%12{/Math}" is value=0>
        True
        <Else />
        False
    </If>
</Loop>

Can I do this entirely within the loop or do I need to increment a variable outside of the loop? Thanks.

1 Like

Hey Phil,
Usually I suggest nth-child selectors to vary styling based on loop count, but that would be a bit messy for this application, so we’ll do it with math! So here’s the full solution:

<Set n_value>0</Set>
<ul>
  <Loop>
    <Set n_remainder><Math><Get loop=count /> % 11</Math></Set>
    <li style="--n: {Get n_value}">
      <figure>
         <img...>
      </figure>
    </li>
    <If variable=n_remainder value=0><Set n_value><Math><Get n_value /> + 1</Math></Set></If>
  </Loop>
</ul>

I started by setting the default n value to 0 before the Loop, otherwise the first 11 items would have no value for the custom CSS property --n: <Set n_value>0</Set>

Next, using math I find the remainder when the loop count is divided by 11 using the modulo operator (%): <Set n_remainder><Math><Get loop=count /> % 11</Math></Set>

Finally, right before the Loop is closed, I test for when the remainder is 0 (which means the loop count is a multiple of 11) and add one to the n value: <If variable=n_remainder value=0><Set n_value><Math><Get n_value /> + 1</Math>

If ever you do want to use the Math tag to do division, keep in mind that it expects / for division. Using the Math tag for something like this is definitely a bit daunting, but outputting values to test your work helps a lot!

Hope this helps!

Indeed, however, this is a pure CSS masonry gallery, and it seems the solution requires having the images in blocks of 11 to organise them properly. Usually, these galleries require some javascript which I try to avoid as much as possible.

Nevertheless, this all works great, thanks! I almost have a full and free gallery solution working, which I can share soon. :slight_smile:

1 Like