Center navbar

1

I would like help centering the following navbar items when viewed on desktop

HTML

<div class="menu" id="menu">
    <a href="#home">Home</a>
    <a href="#news">News</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
    <a href="javascript:void(0);" style="font-size:15px;" class="menu-icon" onclick="menu()">&#9776;</a>
</div>

CSS

.menu {
    overflow: hidden;
    background-color: #333;
}

.menu a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
}

.menu a:hover {
    background-color: #ddd;
    color: black;
}

.menu .menu-icon {
    display: none;
}

@media screen and (max-width: 600px) {
    .menu a:not(:first-child) {
        display: none;
    }
    .menu a.menu-icon {
        float: right;
        display: block;
    }
}

@media screen and (max-width: 600px) {
    .menu.menu-responsive {
        position: relative;
    }
    .menu.menu-responsive .menu-icon {
        position: absolute;
        right: 0    ;
        top: 0;
    }
    .menu.menu-responsive a {
        float: none;
        display: block;
        text-align: left;
    }
}

JS

function menu() {
    var x = document.getElementById("menu");
    if (x.className === "menu") {
        x.className += " menu-responsive";
    } else {
        x.className = "menu";
    }
}
    
asked by anonymous 23.05.2017 / 01:21

1 answer

1

Just change 'float: left' and 'display: block' from '.menu to' by 'display: inline-block', and 'text-align: center' in '.menu' add them in again on the media-screen.

function menu() {
  var x = document.getElementById("menu");
  if (x.className === "menu") {
    x.className += " menu-responsive";
  } else {
    x.className = "menu";
  }
}
.menu {
  width: 100%;
  overflow: hidden;
  background-color: #333;
  text-align: center;
}

.menu a {
  display: inline-block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.menu a:hover {
  background-color: #ddd;
  color: black;
}

.menu .menu-icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .menu a {
    float: left;
    display: block;
  }
  .menu a:not(:first-child) {
    display: none;
  }
  .menu a.menu-icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .menu.menu-responsive {
    position: relative;
  }
  .menu.menu-responsive .menu-icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .menu.menu-responsive a {
    float: none;
    display: block;
    text-align: left;
  }
}
<div class="menu" id="menu">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
  <a href="javascript:void(0);" style="font-size:15px;" class="menu-icon" onclick="menu()">&#9776;</a>
</div>
    
23.05.2017 / 01:34