Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

  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.

like image 429
Vincent Avatar asked Aug 12 '12 12:08

Vincent


People also ask

How do I show and hide elements in CSS?

You can hide an element in CSS using the CSS properties display: none or visibility: hidden . display: none removes the entire element from the page and mat affect the layout of the page. visibility: hidden hides the element while keeping the space the same.

How do you select the first N element in CSS?

The :nth-child selector allows you to select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.

How do I hide the nth child in CSS?

jQuery selector is described in the Selectors/nthChild docs, and the above can be accomplished with $("li. mybutton:nth-child(2)"). hide() .


1 Answers

  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

    .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>
  2. What you're doing is fine.

like image 164
BoltClock Avatar answered Oct 02 '22 16:10

BoltClock