I was having trouble using the nth-of-type(2n+1) selector to target odd and even rows in the scenario below. What I wanted was for the nth-of-type selector to apply different styles to the odd rows with the classes "row-data row-header" and "row-data row-content." Eventually, I had to resort to using jQuery upon document load to manually add an "odd" class to certain rows. Is there a more efficient (CSS-only) method for achieving this?
This is my desired CSS:
.row-data.row-header(2n+1) .col { background-color: #e7e7e7; }
.row-data.row-content(2n+1) .col { background-color: #c8ebed; }
Despite trying variations like using "odd" instead of 2n+1, the above CSS did not produce the desired results. As a workaround, I implemented the following JavaScript logic:
<script>
function alternateRowBackgroundColours()
{
$(".row-header").each(function (i, e)
{
if (i % 2 != 0)
$(this).addClass("odd");
$(".row-content", $(this).next(".row-cnt")).each(function (j, e)
{
if (i % 2 != 0)
$(this).addClass("odd");
});
});
}
$(document).ready(function ()
{
alternateRowBackgroundColours();
});
</script>
Corresponding to the script, I then included the following CSS:
.row-data.row-header.odd .col { background-color: #e7e7e7; }
.row-data.row-content.odd .col { background-color: #c8ebed; }
It should be noted that the number of row-header(s) and their associated row-content(s) is dynamic, and each row-header has a toggle button that reveals its corresponding row-content(s) similar to an accordion.
The outcome of implementing these changes can be visualized https://i.sstatic.net/MuMzT.jpg.