[CSS] Specify CSS only on the left edge of the Grid Layout.

A multi-row, three-column table was created using Grid Layout.

image.

I wanted to apply CSS to the left edge of the row, but I got lost so I had to sort it out.
To apply CSS to the nth element, use the :nth-child() pseudo-class.

目次

CSS is applied every multiple of three.

The first thing I considered was: could CSS be applied to multiples of three? We thought.

:nth-child(3n){}

In this way, the CSS hits every multiple of 3, which is not the intended shape.

image.

Only apply CSS to the leftmost column of the Grid Layout.

To apply only to the left-hand column, this can be achieved by

:nth-child(3n + 1) {}
image.

The n in :nth-child() is a counter starting at 0 and increasing by 1.
Here, 3n + 1 is the result of multiplying the value of n by 3 and adding 1. So when n is 0, 1, 2, 3, 3, 3n + 1 is 1, 4, 7 and the CSS can be applied only to the left-hand end of the three-column table.

Summary

The nth-child is useful and I have sorted it out for myself.
As mentioned in MDN, the odd representing odd numbers (1,3,5,) is internally the same selector as 2n+1, so it’s good to understand why this is the case.

シェア!

この記事を書いた人

kenichiのアバター kenichi エンジニア・写真家 | Engineer and photographer

Nomadic worker who travels all over Japan and abroad; worked as a technical sales person for five years before going independent.
Works as a freelance engineer on website production and application development. Currently working to bring interesting things by interesting people to the world, while seeking to move abroad.

目次