0

I have a navigation bar built using flexbox and would like 3 sections. Links on the left, links on the right, and the logo in the center. However, if I try to use flexbox for this, my logo ends up offset if the content of the links on the left are different from those on the right. So how do I center my logo?

enter image description here

This is the HTML:

<nav>
<div class="logo">
    <img src="img/logo.svg"/>
</div>
<ul>
    <li><a href="/about.html" class="selected">Home</a></li>
    <li><a href="/about.html">About</a></li>
    <li><a href="/about.html">Work</a></li>
    <li><a href="/about.html">Contact</a></li>
</ul>
</nav>

This is the CSS:

nav {
    display: flex;
    text-align: center;
}

nav > .logo {
    flex-grow: 1;
}

nav > .logo > img {
    height: 1rem;
}

nav > ul {
    display: flex;
    margin: 0;
    padding: 0;
    list-style: none;
}

nav > ul > li {
    margin: 0 1rem;
}
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Rjdlee
  • 739
  • 1
  • 6
  • 22

1 Answers1

1

* {
  margin: 0; padding: 0; }

nav {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.logo img {
  width: 200px; }

nav > ul {
    display: flex;
    margin: 0;
    padding: 0;
    list-style: none;
}

nav > ul > li {
    margin: 0 1rem;
}
<nav>
  <ul>
      <li><a href="/about.html" class="selected">Home</a></li>
  </ul>
  <div class="logo">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/2000px-Google_2015_logo.svg.png"/>
  </div>
  <ul>
      <li><a href="/about.html" class="selected">Home</a></li>
  </ul>
</nav>

You don't need to use flex-grow: 1 in logo. You can specify width for logo and use justify-content: space-between; and align-items: center;

align-items: center make your elements vertically align while justify-content: space-between separate your elements equally on free space .

hdotluna
  • 5,514
  • 4
  • 20
  • 31