我正在制作一个带有下拉功能+主页按钮的导航栏。但是,“主页”按钮保留在页面的右上角,而不是与下拉选项一起显示。在此导航栏中,应该有一个主页按钮(位于左侧),其旁边的同一行上有 3 个下拉菜单。但是,主页按钮位于页面的右上角,我不知道如何修复它。这也取自 Codepen 示例,并进行了更改以适应我网站的主题。
这就是导航栏现在的样子:
<header>
<div class="wrapper">
<img src="Images/Favicon.png" class="logo"><span class="color"></span>
<nav class="navbar">
<a href="Index.html">Home</a>
<div class="dropdown">
<button class="dropbtn">Aerospace Engineering</button>
<div class="dropdown-content">
<a href="">Aerodynamics</a>
<a href="#">Aircraft</a>
<a href="">Spacecraft</a>
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Quantum Fields</button>
<div class="dropdown-content">
<a href="#">Mechanics</a>
<a href="#">Physics</a>
<a href="">Computing</a>
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Astronomy</button>
<div class="dropdown-content">
<a href="#">The Stars</a>
<a href="#">Galaxy Types</a>
<a href="#">Black Holes</a>
</div>
</div>
</nav>
</div>
</header>
header {
height: 120px;
position: sticky;
top: 0;
background-color: #21203d;
float: left;
z-index: 10;
}
.logo {
max-width: 120px;
margin-top: 5px;
margin-bottom: 10px;
margin-left: 20px;
background-color: #21203d;
width: 16%;
}
.navbar{
background-color: #21203d;
font-family: Franklin Gothic;
display: inline-block;
font-size: large;
position: absolute;
right: 0;
margin-right: 30px;
}
.navbar a{
color: white;
text-decoration: none;
font-size: large;
float: right;
}
.dropdown{
float: right;
text-align:center;
display: block;
margin-top: 40px;
font-size: large;
}
.dropdown .dropbtn{
font-size: large;
text-transform: uppercase;
font-weight: bold;
border: none;
outline: none;
color: white;
padding: 15px;
background-color: #21203d;
margin: 0;
}
对齐被
position: absolute
和 float: right
的组合破坏。要纠正这个问题:
header
和 .navbar
显示:flex;`。align-items: center
水平对齐项目并使用 gap
作为间距。float
和absolute
定位.navbar
和.dropdown
。更新了CSS
header {
height: 120px;
position: sticky;
top: 0;
background-color: #21203d;
z-index: 10;
display: flex;
align-items: center;
padding: 0 20px;
}
.logo {
max-width: 120px;
margin-right: 20px;
}
.navbar {
display: flex;
align-items: center;
gap: 20px; /* Adds spacing between items */
}
.navbar a {
color: white;
text-decoration: none;
font-size: large;
}
.dropdown {
position: relative;
}
.dropdown .dropbtn {
font-size: large;
text-transform: uppercase;
font-weight: bold;
border: none;
outline: none;
color: white;
padding: 15px;
background-color: #21203d;
cursor: pointer;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown:hover .dropdown-content {
display: block;
}
这会将“主页”和下拉菜单对齐在同一行。让我知道这是否有帮助!