【问题标题】:How to show the first N elements of a block and hide the others in css?如何在css中显示块的前N个元素并隐藏其他元素?
【发布时间】:2012-08-08 23:10:49
【问题描述】:

我正在尝试将具有 .row 类的前 3 个元素隐藏在块 .container 内。

我正在做的是首先隐藏所有.row,然后我尝试使用.row:nth-child(-n+3)显示前3个.row

jsfiddle 在这里:http://jsfiddle.net/z8fMr/1/

.row {
  display: none;
}

.row:nth-child(-n+3) {
  display: block;
}
<div class="content">

  <div class="notarow">I'm not a row and I must remain visible</div>
  <div class="row">Row 1</div>
  <div class="row">Row 2</div>
  <div class="row">Row 3</div>
  <div class="row">Row 4</div>
  <div class="row">Row 5</div>
  <div class="row">Row 6</div>

</div>

我这里有两个问题:

  1. 第 3 行不显示,是不是我用错了 nth-child?
  2. 有没有比隐藏所有内容然后创建特定规则来显示我想要的前 n 个元素更好的做法?在 css 中有没有办法只显示前 3 个 .row 然后隐藏所有其他 .row

谢谢。

【问题讨论】:

  • 我会用 JS 来做这个。

标签: css pseudo-class css-selectors


【解决方案1】:
  1. 您有一个 .notarow 作为第一个孩子,因此您必须在 :nth-child() 公式中考虑这一点。因为那个.notarow,你的第一个.row成为了父母的第二个孩子,所以你必须从第二个开始数到第四个:

     .row:nth-child(-n+4) {
         display: block;
     }
    

    Updated fiddle

    .row {
        display: none;
    }
    
    .row:nth-child(-n+4) {
        display: block;
    }
    <div class="content">
        <div class="notarow">I'm not a row and I must remain visible</div>
        <div class="row">Row 1</div>
        <div class="row">Row 2</div>
        <div class="row">Row 3</div>
        <div class="row">Row 4</div>
        <div class="row">Row 5</div>
        <div class="row">Row 6</div>
    </div>
  2. 你做的很好。

【讨论】:

  • 感谢您对 BoltClock 的非常清晰的解释。我认为 (-n+3) 会选择前 3 个 .row 之前的任何元素。
  • 您是否还知道我想做的事情是否还有最佳实践?隐藏所有内容然后显示前 3 个元素 => 是否有更好的方法仅在 css 中显示前 N 个元素?谢谢
  • 似乎没有更好的方法。像这样使用:nth-child() 就可以了,只要您适应实际结构并且足够可预测。
  • 这里的减号 (-) 有什么作用?
  • @tmyie:它翻转 n 以便从 0 开始倒数,所以你得到 0+4, -1+4, -2+4, -3+4... 导致第 4、3、2 和 1 个孩子。
【解决方案2】:

你甚至不需要 CSS3 选择器:

.row + .row + .row + .row {
    display: none;
}

这在 IE7 中也应该可以工作。
Updated fiddle

【讨论】:

    【解决方案3】:

    另外,像 Giovanni 的解决方案一样,这样的方法也可以工作。

    .container > .row:nth-child(3) ~ .row {
        /* this rule targets the rows after the 3rd .row */
        display: none;
    }
    

    【讨论】:

      【解决方案4】:

      我通过谷歌搜索“css show first n elements”找到了这个答案,但现在的问题似乎是相反的(隐藏前 n 个元素)

      :nth-child(n+4)
      

      ^ 如果您正在寻找我正在寻找的东西,这将起作用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-11
        • 1970-01-01
        相关资源
        最近更新 更多