Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Width of flex items is being reduced

Tags:

html

css

flexbox

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

like image 971
abaracedo Avatar asked Nov 15 '16 20:11

abaracedo


People also ask

How do I fix my flexbox width?

If you want to have a fixed-width column with Flexbox, you need to use the CSS flex or flex-basis property. First of all, we set the display of our <div> container to "flex". Then, we specify the flex of the "grey" class as "0 0 50px".

How do you make a flex item full width?

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100% , and enable wrap on the container. The item now consumes all available space.

Does Flex shrink?

The flex-shrink CSS property sets the flex shrink factor of a flex item. If the size of all flex items is larger than the flex container, items shrink to fit according to flex-shrink .


1 Answers

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?

like image 191
Michael Benjamin Avatar answered Oct 07 '22 01:10

Michael Benjamin