CSS 如何在css中显示块的前N个元素并隐藏其他元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11922165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:46:33  来源:igfitidea点击:

How to show the first N elements of a block and hide the others in css?

csspseudo-classcss-selectors

提问by Vincent

I am trying to hide the first 3 elements having the class .rowinside the block .container.

我试图隐藏.row块内具有该类的前 3 个元素.container

What I'm doing is hiding all the .rowfirst, and then I am trying to display the first 3 .rowby using .row:nth-child(-n+3)

我在做什么是隐藏所有的.row第一,然后我想显示前3.row.row:nth-child(-n+3)

jsfiddle here: http://jsfiddle.net/z8fMr/1/

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

I have two problems here:

我在这里有两个问题:

  1. Row 3 is not displayed, am I using nth-child in the wrong way?
  2. Is there a better practice than hiding everything and then creating a specific rule to display the n first elements that I want? Is there a way in css to just display the first 3 .rowand then hide all the other .row?
  1. 第 3 行未显示,我是否以错误的方式使用了 nth-child?
  2. 有没有比隐藏所有内容然后创建特定规则来显示我想要的第 n 个元素更好的做法?在 css 中有没有办法只显示前 3 个.row然后隐藏所有其他的.row

Thanks.

谢谢。

回答by BoltClock

  1. You have a .notarowas the first child, so you have to account for that in your :nth-child()formula. Because of that .notarow, your first .rowbecomes the second child overall of the parent, so you have to count starting from the second to the fourth:

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

    Updated fiddle

  2. What you're doing is fine.

  1. 你有.notarow第一个孩子,所以你必须在你的:nth-child()公式中考虑到这一点。正因为如此.notarow,你的第一个.row成为父母的第二个孩子,所以你必须从第二个到第四个开始计算:

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

    更新的小提琴

  2. 你在做什么很好。

回答by Giovanni

You don't even need CSS3 selectors:

你甚至不需要 CSS3 选择器:

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

This should work even in IE7.
Updated fiddle

即使在 IE7 中,这也应该有效。
更新的小提琴

回答by Nikhil Girraj

Also, like Giovanni's solution, something like this could also work.

此外,就像乔瓦尼的解决方案一样,这样的事情也可以工作。

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

回答by Tony Ciccarone

I found this answer by Googling "css show first n elements", but the question now seems to be the opposite (hiding first n elements)

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

:nth-child(n+4)

^ this will work if you're looking for what I was looking for

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