Centralize navbar

Asked

Viewed 1,202 times

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";
    }
}

1 answer

1


Just swap the 'float:left' and the 'display:block' of '.menu a' for 'display: inline-block', and 'text-align: center' in '.menu' add them to the 'media-screen' again' .

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.