CSS/Flexbox: Only show as many items as will fit in container

Viewed 2205

My goal is to build a breadcrumb style component which:

  1. shows a horizontal list of items
  2. has a maximum width for each item
  3. omits items from the start of the list if there is insufficient width to show them
  4. prioritises the last item(s) in the list
  5. all layout achieved with CSS only (no JS resize watchers etc)

Flexbox seems like a good place to start, but when it comes to requirements 3&4 I am not sure what the best approach is.

Here's my thought process so far:

a) To start, I could create a flexbox with items like so, each 100px wide:

https://codepen.io/mattwilson1024/pen/LLvMzB

b) Now let's imagine we only have 300px for the container. I could have all items shrinkable (flex: 0 1 100px). This would be fine for a small number of items, but if I have a lot of items they'd all get too small.

https://codepen.io/mattwilson1024/pen/pwBqdN

What I really want is for it to only show as many items as will fit into the container. In this case that would be items 7-9.

c) Enabling flex-wrap: wrap means each row only shows as many items as can fit. This is closer to what I'm after, except I'd only want the bottom row.

https://codepen.io/mattwilson1024/pen/YQMdEB

d) Media queries might help. For example I could use a media query to hide all but the last 3 items on a small screen, and all but the last 6 items on a larger screen etc. However, I would then need to know exactly where the component is going to be used and tweak the numbers accordingly. I'd rather find a solution that is based on the size of the container rather than the size of the viewport.

1 Answers
Related