user1409736
user1409736

Reputation:

Hide all except the first 4 elements

There are endless elements. And I want to do is hide all except the first 4 elements. (with :not selector)

And I want to make a click all visible.. is this possible with css?

<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>/*must hide*/
  <li></li>/*must hide*/
  <li></li>/*must hide*/
  <li></li>/*must hide*/
      ........ /*must hide foreva*/
</ul>

Upvotes: 5

Views: 5924

Answers (3)

Sebastian Brosch
Sebastian Brosch

Reputation: 43594

You can use the following solution, using :nth-child:

ul li:nth-child(n+5) {
  display:none;
}
input[type=checkbox]:checked + ul li {
  display:list-item;
}
<input type="checkbox"/>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ul>

You can use a <input type="checkbox"/> to change the visibility of the items.


You can also use the :nth-child with :not (other way to calculate the hidden items):

ul li:not(:nth-child(-n + 4)) {
  display:none;
}
input[type=checkbox]:checked + ul li {
  display:list-item;
}
<input type="checkbox"/>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ul>

Upvotes: 5

Yahya Hussein
Yahya Hussein

Reputation: 9121

it is easy, you should read about CSS.

use this:

ul li:nth-child(n+4){display:none;}

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122087

You can combine :not() pseudo class and :nth-child().

ul li:not(:nth-child(-n + 4)) {
  display: none;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

Upvotes: 1

Related Questions