我正在遵循w3schools的指南,为我的站点构建一个响应式顶部导航栏:How TO - Responsive Top Navigation
但是,我希望导航项在页面上居中,而不是左对齐或右对齐。w3schools甚至还有关于中心导航元素link的第二个教程,但当我尝试将此代码用于几个导航元素时,它们要么都在彼此内部,要么堆叠在一起!
更让我沮丧的是,之前有一个关于这个确切问题的问题(here),但在此期间,示例的代码似乎发生了很大变化,因此答案不再适用。:(
发布于 2020-03-04 21:16:47
要使您提供的链接中的顶部导航居中,需要将以下内容添加到.topnav
中
.topnav {
…
display: flex;
justify-content: center;
}
要定位移动菜单(而不是居中),请在@media查询中添加以下内容:
@media screen and (max-width: 600px) {
…
.topnav { display: block; }
}
在此之前
之后
发布于 2020-03-04 21:21:10
一种方法是将链接包装在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>
https://stackoverflow.com/questions/60534722
复制