CSS: Menu alignment in header using CSS

Viewed 53
4 Answers

you can add this to the .topnav class

  display: flex;
align-items: center;
justify-content: center;

Use can use the flexbox property to align the menu items across the menu with equal intervals. Just need to change the css in the .topnav class. Like this:


.topnav {
  overflow: hidden;
  background-color: black;
  display:flex;
  justify-content : space-between;
}

Working code:

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {
      margin: 0;
      font-family: Arial, Helvetica, sans-serif;
    }
    
    .topnav {
      overflow: hidden;
      background-color: black;
      display: flex;
      justify-content: space-between;
    }
    
    .topnav a {
      float: left;
      color: #f2f2f2;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      font-size: 17px;
    }
    
    .topnav a.active {
      background-color: #04AA6D;
      color: white;
    }
  </style>
</head>

<body>

  <div class="topnav">
    <a class="active" href="#home">Home</a>
    <a href="#news">News</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
  </div>


</body>

</html>
Hope that's how you wanted it to look.

To center the text in the screen use this

.topnav {
  overflow: hidden;
  background-color: black;
  justify-content: center;
  align-items: center;
  display: flex;
}

Then to configurate the space between the header links you can use this

a{
  margin-left: 2rem;
}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

.topnav {
  overflow: hidden;
  background-color: black;
  
  padding:0 5%;/*It is better to use container*/
  display:flex;
  justify-content:space-evenly;
}

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

.topnav a.active {
  background-color: #04AA6D;
  color: white;
}
</style>
</head>
<body>

<div class="topnav">
  <a class="active" href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
</div>

</body>
</html>

Related