How can I show just the first 5 items in a list with CSS scrolling?
Asked by
CreativePanda42
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?
Answers
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!
Reply to this answer
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.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions