Solution 1 :

This is how you would do it more dynamically with flexbox:
If you add new tabs, it automatically updates. You don’t need to edit your CSS width. That’s why I like flexbox so much. It takes care of everything automatically.

CSS:

   .topnav {
  background-color: #333;
  display: flex;   
}

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

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


.topnav a.active {
  background-color: #4CAF50;
  color: white;
}

Problem :

i am trying to center text in the navigation bar, but for some reason the code does not seem to work and stays on the left side. How can i fix this situation i tried adding different types of code to it to see if the situation would be fixed but still having trouble with centering the text on the navbar

CSS:

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


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

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


.topnav a.active {
  background-color: #4CAF50;
  color: white;
}

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>My Wesbite </title>
    <link rel="stylesheet" type="text/css" href="css/main.css">
</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>
    <div>

        <h1> this is header 1</h1>
        <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

    </div>

</body>
</html>

Comments

Comment posted by DiamondDrake

The issue is the float left, floating takes the elements out of the flow of the page.

Comment posted by timunix

I recommend flexbox. It is the easiest way to structure your html page and it adds responsiveness imho. Don’t mess around with float hardcoding, that is my opinion.

By