【问题标题】:Problem with odd/even child elements in nth-childnth-child 中奇数/偶数子元素的问题
【发布时间】:2011-07-08 21:33:00
【问题描述】:

我有一个这样的网站:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="article_style.css" />
</head>
<body>
    <div class="section">
    <!--<h1>header</h1>-->
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
    </div>
    <div class="section">
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
        <div>
            paragraph
        </div>
    </div>
</body>
</html>

这是 CSS:

div.section
{
    border: 1px solid black;
}
div.section div:nth-child(even)
{
    color: Green;
}
div.section div:nth-child(odd)
{
    color: Red;
}

结果如下:

这没关系,因为在 each 部分中,奇数 div 为红色,偶数为绿色。 但是当我在第一部分的开头添加标题时(示例中的注释代码)我得到了这个:

我不想那样。我希望像以前一样,但只是在第一部分有一个标题。所以首先是标题,然后是红色段落。

【问题讨论】:

    标签: css html css-selectors


    【解决方案1】:
    div > :nth-child(3)     the third child of a div element
    div > :nth-child(even)  every even child of a div element
    div > :nth-child(odd)   every odd child of a div element
    div > :nth-child(3n)    every third child of a div element
    

    【讨论】:

      【解决方案2】:

      改用nth-of-type

      Live Demo

      div.section
      {
          border: 1px solid black;
      }
      div.section div:nth-of-type(even)
      {
          color: Green;
      }
      div.section div:nth-of-type(odd)
      {
          color: Red;
      }
      

      【讨论】:

      • 谢谢,它有效!但是,我不确定如果不看类型,为什么有人会使用nth-child。它有什么用?
      • @CichyK24:经典用例是zebra-striping 表或列表的行。
      • @CichyK24:是的,这也适用于nth-of-type,但它比您需要的更具体。在某些情况下,您只需使用其中一种。仅此一点就意味着两个伪类都是有用的。如果您真的希望我这样做,我将制作一个演示,展示nth-child 做我想做的事情而nth-of-type 不做的情况:)
      • 好的,我明白了。您不必制作演示 ;-) 感谢您的回答!
      • 非常喜欢 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 2013-07-01
      • 2012-01-01
      • 1970-01-01
      • 2018-06-13
      相关资源
      最近更新 更多