How to show the first N elements of a block and h

2019-02-04 00:02发布

问题:

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/

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 .row and then hide all the other .row ?

Thanks.

回答1:

  1. 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;
    }
    

    Updated fiddle

  2. What you're doing is fine.



回答2:

You don't even need CSS3 selectors:

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

This should work even in IE7.
Updated fiddle



回答3:

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;
}