skip to Main Content

I am using css selector to hide elements but I dont know how to do it in nth-child, I want to hide all the remaining elements after the element position 5. How I can do it with nth-child ?

<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="item">item 5</div> 
<div class="item">item 6</div> // hidden
<div class="item">item 7</div> // hidden
<div class="item">item 8</div> // hidden
...etc...

2

Answers


  1. Try this

    div:nth-child(n+6) {
        display: none;
    }
    
    div:nth-child(n+6) {
        display: none;
    }
    <div class="item">item 1</div>
    <div class="item">item 2</div>
    <div class="item">item 3</div>
    <div class="item">item 4</div>
    <div class="item">item 5</div> 
    <div class="item">item 6</div> // hidden
    <div class="item">item 7</div> // hidden
    <div class="item">item 8</div> // hidden

    more details

    Login or Signup to reply.
  2. I tried to select them using :nth-child(n+5), but only the first 3 divs weren’t hidden, not 5. I then tried .item:nth-child(5) ~ .item, but now only 4 were visible. I don’t know what’s up with that, try it for yourself. I think the only workaround is to account for… whatever that error this:

    .item:nth-child(n+7) {display: none;}
    <div class="item">item 1</div>
    <div class="item">item 2</div>
    <div class="item">item 3</div>
    <div class="item">item 4</div>
    <div class="item">item 5</div> 
    <div class="item">item 6</div> <!-- hidden -->
    <div class="item">item 7</div> <!-- hidden -->
    <div class="item">item 8</div> <!-- hidden -->
    <!-- ... -->

    EDIT: Maybe, it’s because that n in :nth-child ranges not from 0, but from -2. IDK.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search