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

求助:如何将Navbar设置在页面顶部右侧并水平显示?

解决方案

这里是调整后的代码,可实现导航栏在页面顶部右侧并水平排列的效果:

CSS 代码

* {
  font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  width: 100%;
  /* 给body添加上边距,避免内容被固定的header遮挡(可选) */
  padding-top: 80px;
}

#header {
  width: 100%;
  position: fixed; /* 让header固定在顶部(可选,滚动时保持导航栏可见) */
  top: 0;
  left: 0;
  background-color: #02082c;
  color: #f9f9f9;
  padding: 15px 0; /* 增加上下内边距,让内容更舒展 */
}

.container {
  width: 85%;
  margin: 0 auto;
  display: flex; /* 让容器成为flex容器,实现左右布局 */
  align-items: center; /* 垂直居中对齐品牌和导航栏 */
  justify-content: space-between; /* 品牌居左,导航栏居右 */
}

.logo {
  color: white;
  text-decoration: none;
}

.navbar {
  list-style: none;
  display: flex; /* 导航项水平排列 */
  align-items: center;
}

.navbar .nav-list {
  margin: 0 15px; /* 增加导航项之间的间距 */
}

.navbar .nav-item {
  font-weight: 600;
  font-size: 18px;
  color: #f9f9f9; /* 设置导航链接为白色,适配深色背景 */
  text-decoration: none; /* 去掉链接下划线 */
}

.navbar .nav-item:hover {
  color: #ccc; /* 鼠标悬停时的颜色变化(可选) */
}

HTML 代码

<section id="header">
  <div class="container">
    <div class="brand">
      <h1><a href="#" class="logo">GOLD</a></h1>
    </div>
    <ul class="navbar">
      <li class="nav-list"><a href="#" class="nav-item">Home</a></li>
      <li class="nav-list"><a href="#" class="nav-item">About Us</a></li>
      <li class="nav-list"><a href="#" class="nav-item">Services</a></li>
      <li class="nav-list"><a href="#" class="nav-item">Contact Us</a></li>
    </ul>
  </div>
</section>

关键修改说明

  • 将 display: flex 和 justify-content: space-between 从 #header 移到 .container:品牌和导航栏都在容器内部,容器作为flex容器才能让两者分别居左、居右。
  • 给 #header 设置 width: 100% 并添加内边距:确保头部占满页面宽度,内容不会紧贴边缘。
  • 给导航链接 .nav-item 设置白色和去掉下划线:保证文字在深色背景上清晰可见,样式更整洁。
  • 可选添加 position: fixed:让导航栏固定在页面顶部,滚动时始终可见,同时给body添加上边距避免内容被遮挡。

内容的提问来源于stack exchange,提问作者Onwuemeri Bright Uwakonye

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:22:57