【问题标题】:color text in divs with two colors using css only - tricky仅使用 css 以两种颜色在 div 中为文本着色 - 棘手
【发布时间】:2014-03-10 19:40:41
【问题描述】:

好的,让我用另一个词重写我的问题,这样它看起来清晰有趣:jsFiddle

我需要一个纯 css 解决方案,根据该行是奇数还是偶数,为文本行着色。

代码示例可以是:

<div class="main">
    <div class="zipcode12345">
        <div class="myclass">red with css</div>
        <div class="myclass">blue with css</div>
        <div class="myclass">red with css</div>
        <div class="myclass">blue with css</div>
        <div class="myclass">red with css</div>
    </div>
    <div class="zipcode23456">
        <div class="myclass">blue with css</div>
    </div>
    <div class="zipcode90033">
        <div class="myclass">red with css</div>
        <div class="myclass">blue with css</div>
        <div class="myclass">red with css</div>
    </div>
    <div class="zipcode11321">
        <div class="myclass">blue with css</div>
        <div class="myclass">red with css</div>
        <div class="myclass">blue with css</div>
        <div class="myclass">red with css</div>
    </div>
</div>

可以用css制作吗?如您所见@ jsFiddle,它没有按预期着色。

所以,主 div 是“main”。 如您所见,内部divs 始终具有格式为“zipcodeXXXXX”的类名。 zipcodeXXXXX 的编号是可变的,myclass 的编号是可变的。 但是,奇数线应始终为红色,偶数线应始终为蓝色。 是否存在纯 css 解决方案?

应该是这样的

.myclass:nth-child(2n+1){
 color:red;
}
.myclass:nth-child(2n){
 color:blue;
}

如果我们可以使用 "zipcodeXXXXX" div,对吧?

谢谢。

【问题讨论】:

  • jsFiddle 更新为jsfiddle.net/xY6T3/1 更加清晰。谢谢。
  • 不,这在您当前拥有的标记结构中是不可能的——nth-child 选择器总是查看其父元素范围内的元素。 (提示在 name ...)
  • 这就是我花了几个小时才决定在这里提问之后的想法:)

标签: css html css-selectors


【解决方案1】:

好的,仅适用于想要找到解决方案的人。

这不是一个解决方案(猜猜为什么? - 与上面的 css 解决方案相同):

jQuery(".main .myclass:nth-child(odd)").css('color', 'blue');

这是一个解决方案:

jQuery(".main .myclass:odd").css('color', 'blue');  

Frédéric Hamidi 解释了here 的差异。

【讨论】:

    【解决方案2】:

    你有没有尝试过这样的事情:

    .myclass:nth-of-type(odd) {
        color: red;
    }
    
    .myclass:nth-of-type(even) {
        color: blue;
    }
    

    我刚刚使用了@James Donnelly 提供的代码。

    【讨论】:

      【解决方案3】:

      只需对父元素和子元素应用不同的奇/偶规则:

      div[class^="zipcode"]:nth-of-type(odd) .myclass:nth-of-type(odd),
      div[class^="zipcode"]:nth-of-type(even) .myclass:nth-of-type(even) {
          color: red;
      }
      
      div[class^="zipcode"]:nth-of-type(odd) .myclass:nth-of-type(even),
      div[class^="zipcode"]:nth-of-type(even) .myclass:nth-of-type(odd) {
          color: blue;
      }
      

      JSFiddle demo.

      【讨论】:

      • 我无法编辑 html。 zipced 是我无法更改或修改的。这就是为什么我正在寻找一个 css 解决方案。它存在吗?谢谢。
      • 请更新您的 JSFiddle 链接,它链接到我的问题,而不是您的解决方案:) 但是,您似乎找到了解决方案。让我再检查几次:)
      • @JamesDonnelly,您的新方法只是根据 .zipcode 是奇数还是偶数子元素来切换奇数和偶数的颜色 - 但如果 @ 的数量仍然不会给出所需的结果987654325@ 元素不是“正确”的元素。
      • CBroe 对吗?请看这里jsfiddle.net/xY6T3/10 第 6 和第 7 弦是蓝色的。
      • 如果字符串的数量是偶数,它会在它之后打破顺序。
      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 2019-12-20
      • 2020-09-16
      • 2017-12-14
      • 1970-01-01
      • 2021-07-19
      • 2014-10-17
      • 1970-01-01
      相关资源
      最近更新 更多