DEV Community

Diego (Relatable Code)
Diego (Relatable Code)

Posted on • Originally published at relatablecode.com on

Simple styling using CSS grid for column groups

columns

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?

Planning it out

Where possible I like to use CSS and not javascript as it tends to be considerably faster. In this case, instead of iterating over the array and manually applying the styling that way, I decided the best way would be to use a CSS pseudo-selector in order to determine which columns should be colored.

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

Example: 
li:nth-child(2) { 
   color: red; 
}
Enter fullscreen mode Exit fullscreen mode

Determining the sequence

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:

example code

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:

https://codesandbox.io/embed/jolly-nobel-27rtv?fontsize=14&hidenavigation=1&theme=dark

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.

Top comments (0)