Search code examples
htmlcssnavigationfixed

Navigation looks wrong when it's fixed


I want the position of my navigation to be fixed. But when I change the position to "fixed" in nav, it looks very weird. Here are two examples: Without fixed position: https://jsfiddle.net/Timowo/3nrvch3c/

<nav>
  <ul>
    <li class="category"><a href="#">Contact</a></li>
    <li class="category"><a href="#">Work</a></li>
    <li class="category active"><a href="#">Home</a></li>
    <li class="logotext">Logo</li>
  </ul>
</nav>

With fixed position: https://jsfiddle.net/Timowo/5aock5k1/

    <nav style="position: fixed;">
  <ul>
    <li class="category"><a href="#">Contact</a></li>
    <li class="category"><a href="#">Work</a></li>
    <li class="category active"><a href="#">Home</a></li>
    <li class="logotext">Logo</li>
  </ul>
</nav>

What do I have to change so it's inline but also fixed?

Thanks!


Solution

  • With position:fixed the element will collapse to the width of the widest descendant..in the absence of a defined width.

    Just set width:100%

    * {
      box-sizing: border-box;
    }
    body {
      margin: 0 auto;
      background-color: red;
    }
    nav {
      transition: all 0.2s ease-in-out;
      position: fixed;
      width: 100%;
    }
    nav ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: transparent;
    }
    nav ul li.logo {
      padding: 14px;
      float: left;
    }
    nav ul li.logotext {
      font-family: Futura;
      color: white;
      font-size: 1.3em;
      padding: 28px;
      text-shadow: 3px 3px black;
    }
    nav ul li.category a {
      display: block;
      color: white;
      text-align: center;
      padding: 30px 20px;
      text-decoration: none;
      font-size: 1.2em;
      float: right;
      font-family: Futura;
      text-shadow: 3px 3px black;
    }
    nav ul li.category:hover a {
      background-color: #212121;
    }
    nav ul li.active a {
      background-color: #212121;
    }
    <nav>
      <ul>
        <li class="category"><a href="#">Contact</a>
        </li>
        <li class="category"><a href="#">Work</a>
        </li>
        <li class="category active"><a href="#">Home</a>
        </li>
        <li class="logotext">Logo</li>
      </ul>
    </nav>