如何创建19×19网格:奇数列红背景,偶数列绿背景?
解决19×19网格列颜色统一问题
原来的代码用nth-child(odd/even)会按所有子元素的顺序交替颜色,换行后就变成了棋盘格,而我们需要的是整列颜色统一——奇数列红,偶数列绿。以下是两种可行的解决方法:
方案1:用容器背景渐变快速实现
这种方法无需给每个单元格单独设置样式,通过网格容器的重复渐变直接实现列颜色效果,代码简洁高效:
body { margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: rgba(255, 255, 255, 0.5); font-family: Arial, sans-serif; } .colored-grid { display: grid; /* 定义19列,每列50px */ grid-template-columns: repeat(19, 50px); /* 定义19行,每行50px */ grid-template-rows: repeat(19, 50px); /* 重复渐变:每100px为一组(红50px+绿50px),19列是奇数,最后一列自动为红色 */ background-image: repeating-linear-gradient(90deg, red 0 50px, green 50px 100px ); width: 950px; /* 19×50px,确保渐变覆盖整个网格 */ } .grid-cell { width: 50px; height: 50px; box-sizing: border-box; background-color: transparent; /* 单元格透明,显示容器背景 */ }
<div class="colored-grid"> <!-- 生成361个网格单元(19×19),可通过JS自动生成 --> <script> const grid = document.querySelector('.colored-grid'); for(let i = 0; i < 361; i++) { const cell = document.createElement('div'); cell.classList.add('grid-cell'); grid.appendChild(cell); } </script> </div>
方案2:用nth-child精准匹配列位置
通过19n + k的公式,精准定位每一行的第k个单元格,给奇数列和偶数列分别设置颜色,兼容性更强:
body { margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: rgba(255, 255, 255, 0.5); font-family: Arial, sans-serif; } .colored-grid { display: grid; grid-template-columns: repeat(19, 50px); grid-template-rows: repeat(19, 50px); } .grid-cell { width: 50px; height: 50px; box-sizing: border-box; } /* 匹配所有奇数列的单元格:每19个元素中的第1、3...19个 */ .grid-cell:nth-child(19n + 1), .grid-cell:nth-child(19n + 3), .grid-cell:nth-child(19n + 5), .grid-cell:nth-child(19n + 7), .grid-cell:nth-child(19n + 9), .grid-cell:nth-child(19n + 11), .grid-cell:nth-child(19n + 13), .grid-cell:nth-child(19n + 15), .grid-cell:nth-child(19n + 17), .grid-cell:nth-child(19n + 19) { background-color: red; } /* 匹配所有偶数列的单元格:每19个元素中的第2、4...18个 */ .grid-cell:nth-child(19n + 2), .grid-cell:nth-child(19n + 4), .grid-cell:nth-child(19n + 6), .grid-cell:nth-child(19n + 8), .grid-cell:nth-child(19n + 10), .grid-cell:nth-child(19n + 12), .grid-cell:nth-child(19n + 14), .grid-cell:nth-child(19n + 16), .grid-cell:nth-child(19n + 18) { background-color: green; }
<div class="colored-grid"> <!-- 插入361个.grid-cell元素,可通过JS生成或手动添加 --> </div>
方案对比
- 方案1:代码量少,实现快,适合现代浏览器场景;
- 方案2:兼容性更好,支持旧版浏览器,样式更灵活可控。
内容的提问来源于stack exchange,提问作者balaji
相关产品推荐
相关产品推荐

