Is it possible to limit the number of items in a dynamic list using CSS only?

Asked

Viewed 65 times

1

Let’s assume that I have a normal auto-complete dynamic list, which has 5 items in the desktop version, and when it is mobile, through media queries I would like it to appear only 3 items, but I don’t want to use overflow or pass a class for each item and hide by name, or use javascript programming, just using CSS, it is possible, for example, to hide the last item I use: ul li:last-child { display: none}, what I want to know exactly is whether there is a way to limit a certain list in CSS by using direct hierarchy in CSS. Like making a crude idea that doesn’t exist, but serves to illustrate what I’m looking for, but that I don’t know a real solution in CSS: ul li:limit(6) { ... }, did you understand the reasoning? I hope so.

<ul>
 <li>item 1</li>
 <li>item 2</li>
 <li>item 3</li>
 <li>item 4</li>
 <li>item 5</li>
</ul>

Example I don’t want:

<ul>
 <li>item 1</li>
 <li>item 2</li>
 <li>item 3</li>
 <li class="hide">item 4</li>
 <li class="hide">item 5</li>
</ul>

1 answer

4


To do with nth-child yes, taking the sixth son forward and giving dispay: none using @media

See the example below and run in full screen to test. In this example no matter how many LI then have in the item 5, they will only appear if the screen is larger than 800px

@media screen and (max-width: 800px) {
  .teste li:nth-child(n+6){
    display: none;
  }
}
<ul class="teste">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
  <li>só aparece em tela larga 6</li>
  <li>só aparece em tela larga 7</li>
</ul>

  • 1

    perfect, thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.