You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odin项目着陆页开发:无法将Navbar置于网站右上角

如何将导航栏固定在页面右上角

我正在进行Odin项目的着陆页开发,希望将Navbar置于网站右上角,但目前它始终显示在左侧。我尝试使用justify-content: space-between属性进行调整,已耗时数小时仍未解决问题,以下是我的代码:

CSS代码

.container{
width:100%;
height:27vh;
background-color: #1f2937;
position:static;
}
.footer{  
position: fixed;
bottom: 0px;
width: 100%;
height: 10vh;
background-color:#1f2937;
color: white;
text-align: center;
justify-content: center;
display: flex;
}

.headerlogo {
font-size: 20px;
font-family: 'Times New Roman', Times, serif;
}
.navbar {
position: fixed;
width: 85%;
margin: auto;
padding: 35px 0;
display: flex;
align-items: center;
justify-content: space-between;
top: -30px;
flex-direction: row;
}  
.navbar ul li {
list-style: none;
display: inline-block;
margin: 0 20px;
color:white;
text-decoration: none;
}

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Website</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="navbar">
        <ul> 
            <li><a href="index.html">header link one</a></li>
            <li><a href="index.html">header link two</a></li>
            <li><a href="index.html">header link three</a></li>
        </ul>
        </div>
    </div>
    <div class="footer">
    Copyright © The Odin Project 2021
    </div>
    
</body>
</html>  

问题根源

你用了justify-content: space-between但没效果,核心原因是.navbar容器里只有<ul>这一个子元素,space-between需要至少两个子元素才能在它们之间分配空间,单个元素自然没法触发该属性的布局效果。

两种解决方法

方法1:直接将导航推到右侧

如果不需要左上角logo,直接修改.navbar的justify-content属性为flex-end,就能把内部的<ul>直接对齐到容器右侧:

.navbar {
position: fixed;
width: 85%;
margin: auto;
padding: 35px 0;
display: flex;
align-items: center;
justify-content: flex-end; /* 替换原有space-between */
top: -30px;
flex-direction: row;
}  

方法2:保留logo+导航的双元素结构(符合Odin项目设计)

如果你的页面原本需要左上角logo+右上角导航的布局,先把logo元素添加到.navbar里,这样space-between就能让两个子元素分别对齐左右两端:

修改后的HTML:

<div class="navbar">
    <div class="headerlogo">Header Logo</div> <!-- 添加logo元素 -->
    <ul> 
        <li><a href="index.html">header link one</a></li>
        <li><a href="index.html">header link two</a></li>
        <li><a href="index.html">header link three</a></li>
    </ul>
</div>

同时调整.headerlogo的样式适配深色背景:

.headerlogo {
font-size: 20px;
font-family: 'Times New Roman', Times, serif;
color: white; /* 添加白色文字 */
}

这样.navbar内有两个子元素,justify-content: space-between会正常工作,实现logo左对齐、导航右对齐的效果。

内容的提问来源于stack exchange,提问作者Tuan Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 14:56:26