Definition

For demonstration purpose, I conduct a simple mockup to use in this tutorial. Here it is.

Before we write the code, don’t forget to dissect the design first. As I told you at the beginning, there are usually 2 or 3 parts in top nav bar. I am going to separate it into “left”, “middle”, and “right”.

Flex to the rescue

Flex is very powerful when dealing with a component that has children inside and need to be responsive, making it the optimal solution in our case.

Step 1 : create Nav (as flex-container) and Left, Middle, Right (as flex-item)

For demonstration purpose, I painted the divs with colors so you can see what happens to them clearly.

Step 2 : add some logo, icon and content.

result from step 2 (a lot of spacing on the right)

I use logo image from google (just pick one) and font-awesome 5.

Step 3 : Align horizontally and fill the space

Now the nav is a flex container, it can align their children centered along the horizontal line by using “align-items” property.

Trick! you can fill space in flex container by stretching children

in this case I want the middle one to stay at the center of the screen, so i will assign “flex: 1” to it.

result after adding “flex: 1” to children

Done!. The rest is what you want to add inside each flex item. Happy Coding.

Explanation

flex: 1; // this is a shorthand syntax // equal to set these properties

flex-basis: 0%;

flex-grow: 1;

flex-shrink: 1;

when you assign “flex: 1” to flex item, the flex-basis will do the job first because there is available space on the right of the screen in flex container. After that, flex-grow will have an effect to all flex item by equally stretched to fill the flex container. As a result, the middle item will stay at the middle of the screen, unless the left or right item has width larger than the current width.

Note, flex-shrink has no effect in this tutorial.

flex-basis

sets the initial main size of a flex item, before any available space is distributed

flex-grow

specify how much available space in flex container should assign to that item.

flex-shrink

specifies the flex shrink factor of a flex item to fill within the flex container

If you still found it confused, read this story.

Wrapping up

If you still don’t get it or what the heck is flex, wait for my next story “Understanding Flex-Box Css before using it”. I will explain how to read, analyze and give you the real world example. Stay tuned, and please feel free to comment below and ask me anything! I’d be happy to talk 👍