Uses of modulus – rows for grids and background colours

There are two things that designers will throw out quite often – box grids with rows, and repeating background colours.

Sounds easy – but go and try it within the WordPress loop (or any other). It can get ugly quickly, but the solution is actually simple: Modulus. In PHP it’s the % sign.

To see what modulus is all about run this simple page:

This will output a list showing when various modulus calculations will output TRUE so you can check in an if statement. For example:

$i % 3 == 2: 
0 :  
1 :  
2 : TRUE 
3 :  
4 :  
5 : TRUE 
6 :  
7 :  
8 : TRUE 
9 : 

Simple example – inserting rows for a grid

Modulus 3 is perfect for creating a 3 column grid (in this case in Bootstrap style) as we can check for when the remainder is 2 which will tell us we are on the 3rd, 6th, 9th etc item. This means we can output the very first and last <div class="row"> tags with no logic, then just use modulus to insert the inbetween </div><div class="row"> to end one row and start another where needed:

More complex example – looping background colours

This time we will use modulus 7 to loop over a list of the colours of the rainbow to set a class that will control the background colour of a div:

This illustrates how the modulus number sets the frequency that the loop repeats, and by checking for different remainders you can identify any point in that loop.

If you’ve got a good use of modulus let me know in the comments.

Leave a Reply

Your email address will not be published.