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
How to show the first N elements of a block and hide the others in css?
提问by Vincent
I am trying to hide the first 3 elements having the class .row
inside the block .container
.
我试图隐藏.row
块内具有该类的前 3 个元素.container
。
What I'm doing is hiding all the .row
first, and then I am trying to display the first 3 .row
by 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:
我在这里有两个问题:
- Row 3 is not displayed, am I using nth-child in the wrong way?
- 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
.row
and then hide all the other.row
?
- 第 3 行未显示,我是否以错误的方式使用了 nth-child?
- 有没有比隐藏所有内容然后创建特定规则来显示我想要的第 n 个元素更好的做法?在 css 中有没有办法只显示前 3 个
.row
然后隐藏所有其他的.row
?
Thanks.
谢谢。
回答by BoltClock
You have a
.notarow
as the first child, so you have to account for that in your:nth-child()
formula. Because of that.notarow
, your first.row
becomes 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; }
What you're doing is fine.
你有
.notarow
第一个孩子,所以你必须在你的:nth-child()
公式中考虑到这一点。正因为如此.notarow
,你的第一个.row
成为父母的第二个孩子,所以你必须从第二个到第四个开始计算:.row:nth-child(-n+4){ display:block; }
你在做什么很好。
回答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
^ 如果您正在寻找我正在寻找的东西,这将起作用