Simple Flexbox method for tabs that switch to a dropdown on mobile

The introduction of Flexbox in mainstream front-end development has completely transformed the way we approach layout in CSS, and all for the better! A long overdue solution to those holy-grail and vertical centering layout issues that have caused many a headache over the last few years - it is finally cross-browser compatible (almost!) and ready for use on a daily basis.

One issue I’ve often come across in responsive development is when you have a tabbed navigation with multiple links that needs to switch to a dropdown on mobile. Thankfully Flexbox gives us a nice solution to this, here’s a simple row of tabs on desktop:

Tabbed navigation on desktop

Here’s what we want to achieve on mobile:

Dropdown navigation on mobile — closed with active tab
Dropdown navigation on mobile - open

Here’s the codepen I did up to demonstrate this method. I’ve used Easytabs.js in this case for the tabs.

The most important Flexbox feature we need to achieve this is Flex order. By using this we avoid the need to use a form select dropdown, which we all know are notoriously difficult to style and not user friendly on mobile.

The magic happens here within the mobile media query:

.tabs-list {
display: flex;
justify-content: space-between;

...
  @include media-query(‘phone’) {
flex-direction: column;
height: 65px;
overflow: hidden;
    li.-active {
-webkit-box-ordinal-group: -1; // fixes older Safari issues
order: -1;
}
}

As you can see we switch the tab list flex direction to column, so each tab stacks on top of one another. Then using Javascript we can simply check what item is active and set it’s flex order to be -1. When you click an item that link is pushed to the very top of the list which makes it work just like a dropdown, magic!

*Note — as we require a set height on the list on mobile to prevent this approach only works when the tab titles are going to be short enough that they won’t split onto two lines on mobile. A workaround could be to just reduce the font-size on mobile.