【问题标题】:How do I start the counting of the nth-child selector only with class "box special" not just "box"?如何仅使用“box special”类而不只是“box”开始计算第 n 个子选择器?
【发布时间】:2015-01-04 16:30:12
【问题描述】:

我想让一些框根据它们是组中的奇数还是偶数框而具有不同的属性,但仅适用于多个类的选择器:但它包括原始 box 类的对象,尽管它不是在 nth-child 的 CSS 选择器中:

http://jsfiddle.net/wLx67r83/

<div class="box">1</div>
<div class="box special">1</div>
<div class="box special">1</div>

.box
{
    width: 100px;
    height: 50px;
    background-color: #e3e3e3;
}

.box.special:nth-child(odd)
{
    background-color: red;
}

.box.special:nth-child(even)
{
    background-color: blue;
}

第三个框应该是蓝色的,但它是红色的!第二个应该是红色的,但它是蓝色的!

【问题讨论】:

  • 因为它是父级的nth-child,而不是类的nth-child
  • @Axel 谢谢。是否有使用 css 检查其在一组兄弟姐妹中的奇数/偶数位置的解决方案?

标签: html css css-selectors


【解决方案1】:

您必须在 css 中更改偶数/奇数。

http://jsfiddle.net/wLx67r83/6/

<div class="box">1</div>
<div class="box special">1</div>
<div class="box special">1</div>

.box
{
    width: 100px;
    height: 50px;
    background-color: #e3e3e3;
}

.special:nth-child(even)
{
    background-color: red;
}

.box.special:nth-child(odd)
{
    background-color: blue;
}

编辑:或者您可以选择公式选项 http://jsfiddle.net/wLx67r83/28/

.special:nth-child(2n+0)
{
    background-color: red !important;
}
.special:nth-child(2n+3)
{
    background-color: blue !important;
}

【讨论】:

  • 这并不能解决问题。可能会在开头添加一个额外的&lt;div class="box"&gt;1&lt;/div&gt;,这会使您的解决方案再次出错。问题是如何从第一个“.special”开始计数?
  • 他的解决方案确实有效,除非将第一个 .special 类设为红色很重要:jsfiddle.net/wLx67r83/14
  • @Axel 它不起作用。你只是碰巧让第二组从偶数开始。你可以在这里看到问题:jsfiddle.net/wLx67r83/22
  • 你能用 (an + b) 这样的公式吗,它必须是偶数和奇数吗?例如jsfiddle.net/wLx67r83/28
【解决方案2】:

nth-child 从父节点的子节点开始计数。正确答案是nth-of-type

.box.special:nth-of-type(odd)
{
    background-color: red;
}

.box.special:nth-of-type(even)
{
    background-color: blue;
}

【讨论】:

  • 但这会产生与您原来的小提琴完全相同的结果? jsfiddle.net/wLx67r83/2
  • @Axel 奇怪的是,你是对的。它适用于我自己的网页,但不适用于 jsfiddle!为什么?
  • 不知道,但nth-childnth-of-type 的行为相似,因为它从父级计算。你想要的是nth-of-classbut that doesn't exist in CSS。最好将特殊的 div 包装在自己的父 div 中以保证正确的结果。
猜你喜欢
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多