Create a tab bar with flex-box layout

Recently I am asked to create a tab bar which is supposed to work like the one on Chrome browser. To be more specific, when the tabs don't take up the full width, they have a fixed size. When the total width of the tabs is over the the bound of the tab bar, the tabs should shrink and divide the bar space evenly.

I tried out several solutions, most of them just got the tab bar overflowed or increased the width of the tab bar. Eventually, my hunch was telling me that this was a best use case of using flex-box layout. I knew flex-box quite a while and made use of it in many situations. However, justify-content, align-items, and flex-direction are three properties I used most. I realized that there were some other properties that I thought I knew, but I actually didn't understand how to take a full advantage of them. They are flex-grow, flex-shrink, and flex-basis. And the most tricky one is flex-basis. It defines the default size of an element before the remaining space is distributed. Its default value is 'auto' which means it looks at the width and height property. It's worth noting that the container component should have an indicative size before these three flex rules kick in.

First, we give a fixed width to tab container and apply flex layout to it.

.container {
  display: flex;
  justify-content: flex-start;
  height: 40px;
  width: 500px;
  border: 1px solid #000;
  background: #acacac;
  float: left;
}

For tabs, flex-grow is set to 0 which means its size is based off the flex-basis when there are remaining space in the container. On the other hand, flex-shrink is 1 which means the tabs are distributed evenly based on the width of the container if the container is out of empty space.

.tab {
  flex-grow: 0;
  flex-shrink: 1;
  flex-basis: 100px;
  height: 100%;
  border: 1px solid #a00;
  background: red;
}

Viola! Now we have a tab bar just works like any others. Here is a demo you can play around with.