12

I'm trying to make a navigation menu which will be scrollable horizontally in mobile. To do that I want to do it using flexbox but when I set the mobile view the width of the navigation items is reduced.

I tried using the flex-grow and flex-basis properties setting them to 1 and 0 respectively but it didn't work.

In this case I'm using dummy names for the navigation sections, but they can be of different length.

ul {
  display: flex;
  margin: 0;
  padding: 0;
  list-style: none;
  background-color: #f2f2f2;
  overflow-y: hidden;
  overflow-x: auto;
}

li {
  flex-grow: 1;
  flex-basis: 0;
  margin-left: 10px;
}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

Codepen sample

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
abaracedo
  • 1,404
  • 5
  • 26
  • 45

2 Answers2

17

Keep in mind that an initial setting of a flex container is flex-shrink: 1.

This means that, by default, flex items are allowed to shrink. This prevents them from overflowing the container.

To disable this feature use flex-shrink: 0.

So, for your li, you can try this (shorthand version):

flex: 1 0 auto  (can grow, cannot shrink, initial main size based on content)

More details here: What are the differences between flex-basis and width?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

Use

min-width

or

max-width

instead

NAVNEET CHANDAN
  • 268
  • 3
  • 7