Is it possible to select a specific grid column or row with CSS?
For example, say I have a 3 row by 2 column CSS Grid Layout: grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr;
. How would I select all elements from the 2nd column? For example: grid:nth-child(column:2)
(just my idea, not valid code).
I have tried nth-child
selectors on the div
elements, but this does not allow me to specify row or column when the items are automatically placed by the Grid Layout engine.
To style an arbitrary row, you could use a wrapper element with its display
set to contents
. See the code snippet below:
.grid-container {
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-gap: 2px;
}
.grid-item {
border: 1px solid black;
padding: 5px;
}
.grid-row-wrapper {
display: contents;
}
.grid-row-wrapper > .grid-item {
background: skyblue;
}
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-row-wrapper">
<div class="grid-item">6</div>
<div class="grid-item">7</div>
<div class="grid-item">8</div>
<div class="grid-item">9</div>
<div class="grid-item">10</div>
</div>
<div class="grid-item">11</div>
<div class="grid-item">12</div>
<div class="grid-item">13</div>
<div class="grid-item">14</div>
<div class="grid-item">15</div>
<div class="grid-item">16</div>
<div class="grid-item">17</div>
<div class="grid-item">18</div>
<div class="grid-item">19</div>
<div class="grid-item">20</div>
</div>
EDIT: As with all implementations, you should check to ensure it works in your target environment(s). You can check the compatibility table on MDN or caniuse.com for support for display: contents
: