问题
I'm trying to replace a grid of data & interactive components that had been set up in Bootstrap with a CSS Grid-based layout.
I was able to replicate the grid, but am having trouble getting something like table striping working.From what I understand of CSS Grid, since I know the number of columns that will be displayed ahead of time but not the number of rows (dynamically generated data from the server), I need to use grid-template-columns: repeat(3, auto);
, and each cell must be a direct child of the wrapper div.
I've tried using nth-child to get the effect I want, but can't figure out what selector would let me target a dynamic range of elements.
Is there a better way to set up a grid layout using CSS Grid when the number of rows is unknown ahead of time?
Here's a fiddle with what I have so far, which includes all the code below. In my real project, the rows are dynamically generated and there are 5 columns right now- though that may change in the future.
.grid-table {
display: grid;
display: -ms-grid;
grid-template-columns: repeat(3, auto);
-ms-grid-template-columns: repeat(3, auto);
}
.grid-table :nth-child(-n+3) {
background-color: red;
}
<div class="grid-table">
<span>Room Name</span>
<span>Start Date</span>
<span>End Date</span>
<span>Room 100</span>
<span>Tuesday</span>
<span>Wednesday</span>
<span>Room 200</span>
<span>Tuesday</span>
<span>Friday</span>
<span>Room 200</span>
<span>Tuesday</span>
<span>Friday</span>
<span>Room 200</span>
<span>Tuesday</span>
<span>Friday</span>
</div>
回答1:
Use a selector that targets every other row in one column.
For other columns, simply adjust and repeat.
.grid-table {
display: grid;
grid-template-columns: repeat(3, auto);
}
.grid-table > span:nth-child(-n+3) {
background-color: red;
}
.grid-table > span:nth-child(6n+4),
.grid-table > span:nth-child(6n+5),
.grid-table > span:nth-child(6n+6) {
background-color: lightgreen;
}
<div class="grid-table">
<span>Room Name</span>
<span>Start Date</span>
<span>End Date</span>
<span>Room 100</span>
<span>Tuesday</span>
<span>Wednesday</span>
<span>Room 200</span>
<span>Tuesday</span>
<span>Friday</span>
<span>Room 200</span>
<span>Tuesday</span>
<span>Friday</span>
<span>Room 200</span>
<span>Tuesday</span>
<span>Friday</span>
<span>Room Name</span>
<span>Start Date</span>
<span>End Date</span>
<span>Room 100</span>
<span>Tuesday</span>
<span>Wednesday</span>
<span>Room 200</span>
<span>Tuesday</span>
<span>Friday</span>
<span>Room 200</span>
<span>Tuesday</span>
<span>Friday</span>
<span>Room 200</span>
<span>Tuesday</span>
<span>Friday</span>
</div>
来源:https://stackoverflow.com/questions/44936917/table-striping-rows-in-css-grid