問題描述
我試圖隱藏塊 .container
內具有類 .row
的前 3 個元素.
I am trying to hide the first 3 elements having the class .row
inside the block .container
.
我正在做的是首先隱藏所有 .row
,然后我嘗試使用 .row 顯示前 3 個
.row
:nth-child(-n+3)
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 在這里:http://jsfiddle.net/z8fMr/1/
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>
我這里有兩個問題:
- 第 3 行不顯示,是不是我用錯了 nth-child?
- 有沒有比隱藏所有內容然后創建特定規則來顯示我想要的前 n 個元素更好的做法?css 中有沒有辦法只顯示前 3 個
.row
然后隱藏所有其他.row
?
- 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
?
謝謝.
推薦答案
您有一個
.notarow
作為第一個孩子,因此您必須在:nth-child()
公式中考慮這一點.由于那個.notarow
,你的第一個.row
成為了父級的第二個孩子,所以你必須從第二個到第四個開始計數:
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;
}
更新小提琴
.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>
你做的很好.
這篇關于如何在css中顯示塊的前N個元素并隱藏其他元素?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!