What's the best way to select the specific items in a row?
For example, let's make the div.test
which index are odd to be background-color: red;
on odd row, and div.test
which index are even to be background-color: blue;
on even row.
I can hard code it like my example below, but is there any better way of doing this?
The reason I don't use nth-child(odd)
and nth-child(even)
is that the styling of odd items in odd row is different from even items in even row. You will get the idea of running the code snippet.
#ct {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
grid-row-gap: 10px;
grid-column-gap: 10px;
}
.test {
height: 100px;
}
.test:nth-child(1),
.test:nth-child(3),
.test:nth-child(6),
.test:nth-child(8) {
background-color: red;
}
.test:nth-child(2),
.test:nth-child(4),
.test:nth-child(5),
.test:nth-child(7) {
background-color: blue;
}
<div id="ct">
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
CodePudding user response:
You can use nth-child(odd)
or nth-child(even)
to select the respective rows.
CodePudding user response:
as you dont want to use .test:nth-child(even) & .test:nth-child(odd)
are you willing to use JS OR SASS ? or need to code this in CSS only ?
CodePudding user response:
This is a solution by changing the html structure a little bit.
Important Note: This will only work if you could have ability to change html structure.
#ct {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
grid-row-gap: 10px;
grid-column-gap: 10px;
margin-bottom: 20px;
}
.test {
height: 100px;
}
#ct:nth-child(odd)>.test:nth-child(odd) {
background-color: red
}
#ct:nth-child(odd)>.test:nth-child(even) {
background-color: blue
}
#ct:nth-child(even)>.test:nth-child(odd) {
background-color: blue
}
#ct:nth-child(even)>.test:nth-child(even) {
background-color: red
}
<div id="ct">
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
<div id="ct">
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
P.S.: This seems longer and more mess than your code, but it will be much easier and shorter than your code if you have a lot of them (grid).