Reputation: 38
I am following a guide from w3schools to build a responsive top navigation bar for my site: How TO - Responsive Top Navigation
However, I would like the navigation items to be centered on the page, not aligned to the left or right. w3schools even has a second tutorial on a center navigation element link, but as soon as I try to use this code for several navigation elements, they either are all within each other or stack on top of each other!
Even more to my dismay, there has been a question about this exact problem before (here), but it seems the code of the example has been changed a lot in the meanwhile so that the answer is no longer applicable. :(
Upvotes: 1
Views: 433
Reputation: 19111
To center the top navigation in the link you've provided, you would add the following to .topnav
:
.topnav {
…
display: flex;
justify-content: center;
}
To address the mobile menu (and not center it), add the following to your @media query:
@media screen and (max-width: 600px) {
…
.topnav { display: block; }
}
Upvotes: 2
Reputation: 6902
One way is to wrap the links inside a div (say, a div with class nav-links
), and then applying to the div:
.nav-links {
width: fit-content; /* 'margin: auto' alone does not work if the div takes full width */
margin: auto;
}
Below is a demo based on the tutorial you linked:
.nav-links {
width: fit-content;
margin:auto;
}
/*////////////// W3Schools CSS code //////////////*/
/* Add a black background color to the top navigation */
.topnav {
background-color: #333;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
/* Change the color of links on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* Add an active class to highlight the current page */
.topnav a.active {
background-color: #4CAF50;
color: white;
}
/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
display: none;
}
<!-- Load an icon library to show a hamburger menu (bars) on small screens -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="topnav" id="myTopnav">
<div class="nav-links">
<a href="#home" class="active">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
</div>
Upvotes: 0