Recently, I was tasked with creating a scheduler component. Although this article won’t go into full detail on how it’s being implemented one thing that I had to do was set up the layout (obviously).
I decided that the best course of action for this was to use a CSS Grid to lay everything out. One of the requirements is that it was necessary to have column groups with different color backgrounds. Simple enough right?
Luckily enough there exists a pseudo-class called nth-of-child and nth-of-type. These can be used to dynamically apply a set of CSS styling to a specific number of children. How you may ask? Well the selector can be used in conjunction with simple math to plan it out
Within the selector we have the option to select a child with the following operation: an + b So for example, if we were to just list out nth-child(3) it would be the third child. With the following sequence nth-child(2n) it would be every second child starting with the second.
In my particular case, I had to group up the columns by 4 and style them that way.
What I ended up going with was the following sequence:
With this, we are grouping up the columns by 8 and only coloring the second group of columns as by subtracting I am targeting the final four each time.
Here is the provided example:
And that’s it! Let me know if you have any questions or if you have a preferred method of applying styling to columns/rows using a CSS grid!
Originally published at https://relatablecode.com on November 15, 2021.