Hide all except the first 4 elements

独自空忆成欢 提交于 2021-02-09 20:51:36

问题


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>

回答1:


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>



回答2:


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>



回答3:


it is easy, you should read about CSS.

use this:

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


来源:https://stackoverflow.com/questions/42365235/hide-all-except-the-first-4-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!