如何显示块的前N个元素并将其他元素隐藏在CSS中? [英] How to show the first N elements of a block and hide the others in css?
问题描述
我试图将 .row
类的前三个元素隐藏在 .container
块中。 / p>
我正在做的是先隐藏所有 .row
,然后尝试显示前3个 .row
通过使用 .row:nth-child(-n + 3)
jsfiddle此处: http://jsfiddle.net/z8fMr/1/
.row {
display:none;
}
.row:nth-child(-n + 3){
display:block;
}
< div class = content >
< div class = notarow>我不是一行,我必须保持可见< / div>
< div class = row>行1< / div>
< div class = row>行2< / div>
< div class = row>行3< / div>
< div class = row>行4< / div>
< div class = row>行5< / div>
< div class = row>行6< / div>
< / div>
我有两个问题此处:
- 第3行未显示,我是否以错误的方式使用了nth-child?
- 有吗?比隐藏所有内容然后创建特定规则以显示所需的n个第一个元素更好的做法? CSS中是否有办法只显示前三个
.row
,然后隐藏所有其他.row
吗?
谢谢。
-
您的第一个孩子有一个
.notarow
,因此您必须在:nth-child()<中进行说明/ code>公式。由于存在
.notarow
,因此您的第一个.row
成为父级的第二个子代,因此您必须计算从第二个到第四个开始:.row:nth-child(-n + 4){
显示:块;
}
-
您在做什么很好。
I am trying to hide the first 3 elements having the class .row
inside the block .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)
jsfiddle here: 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>
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
?
Thanks.
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.
这篇关于如何显示块的前N个元素并将其他元素隐藏在CSS中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!