8

I have an indefinite amount of div elements (pieces of content / grid items). I want them to layout in a defined number of columns of CSS Grid. The CSS Grid lays them out like that easily. But now as the elements are in place I'd like to style the <div>s in every other row of the resultant grid in some way.

Think of it as styling every other row of table to a darker color.

This question can be generalised to asking: can you style an arbitrary row/ column of a CSS Grid?

Proposed situation:

<div class="content-grid">
    <div class=""content-grid__item></div>
    <div class=""content-grid__item></div>
    <div class=""content-grid__item></div>
    ...

</div>

The css for it:

.content-grid {
    display: grid;
    grid-template-columns: 77px 77px 77px;
}

.content-grid__item {
    background-color: red;
}

And the preferable solution in of the ideal world:

// pseudocode
.content-grid:nth-row(odd) .content-grid__item {
    background-color: darkred;
}
wiktus239
  • 1,404
  • 2
  • 13
  • 29
  • Could you include any code with the question, thanks – sol Sep 27 '17 at 15:04
  • @ovokuro Sure, there you go :) – wiktus239 Sep 27 '17 at 15:19
  • I found a way using a grid inside a grid to do exactly this, you just need a "row" wrapper - basically simialr to the old tr trick https://gist.github.com/alpha1/3338eab759cc7b8c9ac6c058ecb8c633 – alpha1 Oct 02 '19 at 05:15
  • The correct answer should be: https://stackoverflow.com/questions/3084261/alternate-table-row-color-using-css – RMorrisey Oct 04 '19 at 20:49
  • @RMorrisey Why it should be the correct answer? It uses tables, not grids, which is what the OP wanted to know. – Luca Bezerra Mar 02 '20 at 20:25
  • If you use a row wrapper approach as alpha1 mentioned, you can use nth-child just like in the given answer. – RMorrisey Mar 03 '20 at 19:03
  • Alternately, if the number of items in each row is known (e.g. 5 items), you can use nth-child(5n-1) as explained in this answer: https://stackoverflow.com/a/56315469/166850 – RMorrisey Mar 03 '20 at 19:06

1 Answers1

1

You can't...

CSS Grid rows are not DOM elements and so cannot be selected by CSS.

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
  • 4
    That is true - they are not. But at the same time that doesn't prevent one from "styling every other row of [such] a CSS Grid". I'm asking how – wiktus239 Sep 27 '17 at 15:43
  • Since the aren't elements they aren't stylable with CSS, It's that simple. – Paulie_D Sep 27 '17 at 15:58
  • 3
    Just as an inspiration: http://keithclark.co.uk/articles/targeting-first-and-last-rows-in-css-grid-layouts/ – wiktus239 Sep 28 '17 at 08:07
  • you can work out using nth item type CSS to style say every cell in an odd numbered row by counting columns but you can't say style a background image that spans a row, which you can with css:display table/table-row/table-cell – James Cat Oct 26 '20 at 09:51