所以基本上我有一个向左漂浮的导航栏。该页面具有响应性,因此当屏幕低于一定大小时,导航栏将消失(Home链接除外),并在右侧弹出一个汉堡包下拉菜单。我想要做的是弄清楚如何使导航栏居中并在屏幕尺寸减小并且汉堡包图标出现并在屏幕上居中时完全消失。
HTML:
<div class="topnav" id="myTopnav">
<nav>
<a href="home.html">Home</a>
<a href="history.html">History</a>
<a href="information.html">Information</a>
<a href="gallery.html">Gallery</a>
<a href="videos.html">Videos</a>
<a href="exercises.html">Exercises</a>
<a href="contact.html">Contact</a>
<a href="links.html">Links</a>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">☰</a>
</nav>
</div>
CSS:
/* Add a black background color to the top navigation */
.topnav {
background-color: #000000;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.topnav a {
float: left;
display: block;
color: #FFFFFF;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 2.25em;
margin-bottom: 1.25%;
}
/* Change the color of links on hover */
.topnav a:hover {
background-color: #2C3539;
color: #FFFFFF;
}
/* Add an active class to highlight the current page */
.active {
background-color: #4CAF50;
color: white;
}
/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
display: none;
}
/* When the screen is less than 600 pixels wide, hide all links, except for
the first one ("Home"). Show the link that contains should open and close
the topnav (.icon) */
@media screen and (max-width: 600px) {
.topnav a:not(:first-child) {display: none;}
.topnav a.icon {
float: right;
display: block;
}
}
/* The "responsive" class is added to the topnav with JavaScript when the
user clicks on the icon. This class makes the topnav look good on small
screens (display the links vertically instead of horizontally) */
@media screen and (max-width: 600px) {
.topnav.responsive {position: relative;}
.topnav.responsive a.icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
}
使用Javascript:
<script>
/* Toggle between adding and removing the "responsive" class to topnav when
the user clicks on the icon */
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
如果有任何帮助,我们将不胜感激!
答案 0 :(得分:1)
删除浮动和显示:阻止,并使用内联块可以解决您的问题
display: inline-block;
/* Add a black background color to the top navigation */
.topnav {
background-color: #000000;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.topnav a {
display: inline-block;
color: #FFFFFF;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 2.25em;
margin-bottom: 1.25%;
}
/* Change the color of links on hover */
.topnav a:hover {
background-color: #2C3539;
color: #FFFFFF;
}
:d