You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为无网格项的CSS Grid奇数列设置灰色背景?

给无网格项的CSS Grid奇数列设置灰色背景

因为网格内没有任何网格项,无法通过nth-child等选择器直接针对列元素设置样式,此时可以利用背景渐变来模拟奇数列的灰色效果,具体实现如下:

修改.grid的CSS样式,添加background属性:

.grid {
  display: grid;
  grid-template-columns: repeat(27, minmax(0, 1fr));
  grid-template-rows: repeat(6, minmax(0, 1fr));
  height: 50rem;
  width: 50rem;
  /* 关键:用重复渐变实现奇数列灰色 */
  background: repeating-linear-gradient(
    to right,
    #ccc 0 calc(100%/27),
    transparent calc(100%/27) calc(200%/27)
  );
}

原理说明

  • 网格共有27列,每列宽度为容器总宽度的100%/27
  • repeating-linear-gradient创建一个重复的横向渐变周期:每个周期包含一段灰色(对应1列)和一段透明(对应1列)
  • 由于总列数是奇数(27),最后一个周期只会显示灰色段,刚好覆盖第27列(奇数),完美匹配需求

完整的HTML/CSS代码如下:

<!DOCTYPE html>
<html>
<head>
<style>
.grid {
  display: grid;
  grid-template-columns: repeat(27, minmax(0, 1fr));
  grid-template-rows: repeat(6, minmax(0, 1fr));
  height: 50rem;
  width: 50rem;
  background: repeating-linear-gradient(
    to right,
    #ccc 0 calc(100%/27),
    transparent calc(100%/27) calc(200%/27)
  );
}
</style>
</head>
<body>

<div class="grid">
  <!-- 无网格项 -->
</div>

</body>
</html>

内容的提问来源于stack exchange,提问作者Matan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 12:25:12