Nav With Logo Image

Today I want to highlight my all time favorite method for making a nav -- using flexbox. Although it does have some quirks, the flexible box is supported by almost every browser. You can check out to determine if flexbox is the right solution for your target browser.

Here is a way to centre the nav element. First, set up your nav inside of the 'nav' semantic tag. For the purpose of this exercise I just used a div to display the nav, however putting it inside a separate ul>li element is also fine.

  <div class="logo">
    <a href="#">Logo</a>
    <li><a href="#">About</a></li>
    <li><a href="#">Work</a></li>
    <li><a href="#">Contact</a></li>

Next add a background color for the nav so we know where it is and set its width. If you set a width and want to keep it centred, we add the margin:0 auto to nicely centre our nav. After that we can flex it! Setting display to flex makes all the children of this element take up width of the parent. By default this works in the direction of row(left to right).

  margin:0 auto;

At the bottom we defined "align-items" as centre. This aligns the elements within the box to their centre. If you have a logo that will be a different size than your list items, this will align them automatically.

Now we want to get rid of the default styling on the ul tags, and remove the default list-style from the li tags. We set the ul's display to flex. This pulls the li elements inline.


This next part we take the logo div, and give it the following properties.


What this does: Setting the logo's width to auto so it takes up the amount of space generated by the content that will be there. Then we set margin-right:auto. This dictates the amount of space between elements to automatically be calculated by the browser. Since the logo now has a specific width, and the elements need to take up 100% of the space in flexbox, all the empty space will get pushed until our ul element is right up against the right side.

Finally we can style the a tags with some padding and hover effects.Normally a tags are set to inline display, so styling left and right margin/padding will not work. We have to add display:block to our anchor tags if we want the padding to be applied vertically and horizontally.

  padding:10px 15px;

Below is the full codepen for reference