【问题标题】:How can I create an alternating list pattern with just CSS [duplicate]如何仅使用 CSS 创建交替列表模式 [重复]
【发布时间】:2021-03-01 10:18:33
【问题描述】:

我有一个在 991 像素及以上的屏幕上具有交替颜色图案的项目列表。我正在使用 CSS 来定位每个要更改颜色的子元素。

但是,我的 CSS 看起来不是很优雅,因为项目的数量是未知的,可能有数百个。使用我的 CSS 方法,我必须写出所有可能性以确保保留样式。

有没有一种 CSS 方法可以改进我的方法?

@media screen and (min-width:991px) {

    .item {
        background:darkgrey;
    }

    .item:nth-child(2),
    .item:nth-child(3),
    .item:nth-child(6),
    .item:nth-child(7),
    .item:nth-child(10),
    .item:nth-child(11),
    .item:nth-child(14),
    .item:nth-child(15),
    .item:nth-child(18),
    .item:nth-child(19),
    .item:nth-child(22),
    .item:nth-child(23),
    .item:nth-child(26),
    .item:nth-child(27) ,
    .item:nth-child(30)  {
        background:green;
    }
}

【问题讨论】:

  • 为了更清楚一点:这看起来像是在改变颜色,但实际上它是蓝色、绿色、绿色、蓝色蓝色、绿色、绿色等......所以这并不是真正的重复以上问题。

标签: css


【解决方案1】:

您可以使用functional notation

.item:nth-child(4n+2),
.item:nth-child(4n+3) { background: green }

【讨论】:

  • even2n 与 OP 代码中提到的 2, 3, 6, 7 等不同。
  • @pavel 确实,已修复。我误读了这个问题。
  • 我不知道为什么这被否决了。见w3.org/Style/Examples/007/evenodd.en.html
  • @Roel:这是我的反对意见,请阅读我上面的评论(以及编辑之前的原始答案)。
猜你喜欢
  • 2015-12-26
  • 2013-05-25
  • 2014-04-06
  • 2018-06-16
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
相关资源
最近更新 更多