The Flexible Box Module, or Flexbox, is a more efficient way to layout and align elements in a container when their size is either unknown or dynamic. The size of elements inside the container are adjusted to fill the container size and prevent overflow.
CSS Tricks has an excellent tutorial on using Flexbox: A Complete Guide to Flexbox
A Basic Flexbox Navigation Menu
After setting up some basic styling, such as list-style-type, text-decoration, and background and text colors, we add the Flexbox styling:
- First, we set display: flex; on our nav ul . This is the parent element of our list items, and it is this element that will determine the alignment of its child elements.
- We set the flex-direction: to row , so the elements will be aligned along the x-axis.
- We want our elements to be centered along the x-axis, but with space on either side, so we set justify-content: to space-around .
That’s it! Our nav is now using flexbox to align the list items in a row. If you adjust the size of the screen, you will see that the element size and spacing is adjusted automatically to fit the available space. The elements are even compressed at very small screen sizes (to a point) to prevent any overflow.
You can also use flexbox for a mobile navigation menu:
Vertical Flexbox Navigation Menu
- In this case, we change the flex-direction: to column , so the items are aligned along the y-axis.
- We removed the justify-content: style, because we want our elements to align directly underneath one another.
The benefit of doing this is that you can simply adjust the flex-direction at a larger viewport using media queries when you need to switch to a horizontal menu.
Vertically Centering an Element Using Flexbox
- First, we give our container a set width and height. For many browsers, a defined height is required to vertically center an object using flexbox.
- Give the container display: flex;
- Set the flex-direction: column; so the elements will be aligned along the y-axis.
- justify-content: space-around; will vertically center the div in the container.
- align-items: center; will center the element along the x-axis.
There are some issues with using Flexbox and some versions of IE, including IE 11. See the Known Issues Tab of CanIUse to see these issues and offer a fallback, if necessary.
Navigation Menu With Flexbox and Fallback
Just in case your user is using a browser that doesn’t support flexbox, you should add some fallback CSS. This will be overridden by flexbox, if the browser supports it.
For a centered nav:
- Add a text-align: center; to the nav element.
- Give all nav li elements a display: inline-block and a margin: 1em;
The elements won’t be perfectly spaced as they are in flexbox, but the nav elements will still be centered. This is an example of progressive enhancement.