How can I show just the first 5 items in a list with CSS scrolling?

0
7
Asked By CreativePanda42 On

I'm trying to create a list that only displays the first 5 items but allows users to scroll to see more without using JavaScript. I've heard that I could set a maxHeight property and use overflowY auto, but I really want to avoid setting fixed height values. Is there a way to achieve this purely with CSS?

2 Answers

Answered By CSSNinja99 On

I totally get why you'd want to avoid hardcoding numbers! Unfortunately, to show just 5 items and make the rest scrollable, you usually need to set either a height or max-height. CSS doesn’t have a straightforward way to just limit the display to 5 child elements. One trick you could use is:

```css
ul {
display: block;
overflow-y: auto;
max-height: calc(1.5em * 5); /* assuming each li is around 1.5em high */
}
```

This way, the height is tied to the font size rather than a fixed pixel value, making it a bit more flexible.

Answered By DesignGuru88 On

I hear you about the hassle of using set values! The CSS method does require some sort of max-height unless you're willing to get really creative. Unfortunately, without JS or a max-height setting, there's no clean solution to limit it specifically to 5 items and have scroll functionality. But if you find a workaround, I'm all ears!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.