我正在按照w3schools的指南为我的网站构建一个响应式顶部导航栏:How TO - Responsive Top Navigation
但是,我希望导航项在页面上居中,而不要左右对齐。 w3schools甚至还提供了有关中心导航元素link的第二篇教程,但是一旦我尝试将此代码用于多个导航元素,它们要么都在内部,要么彼此堆叠!
[令我更加沮丧的是,在(here)之前曾有一个关于此确切问题的问题,但与此同时,示例代码似乎发生了很大变化,因此答案不再适用。 :(
一种方法是将链接包装在div(例如,具有类nav-links
的div中),然后应用于div:
.nav-links {
width: fit-content; /* 'margin: auto' alone does not work if the div takes full width */
margin: auto;
}
下面是基于您链接的教程的演示:
.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>