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

如何让导航栏占满父容器宽度?修复右侧多余空间问题

解决导航栏右侧多余空间的问题

问题出在CSS盒模型的默认行为上:默认box-sizing: content-box时,元素设置的width仅代表内容区域宽度,padding和border会额外增加元素的总宽度。你的.primary-navigation设置了width: 100%,再加上padding: 1rem和border: 2px,总宽度就超过了父容器,导致右侧出现多余空间。

修复方案

推荐给元素添加box-sizing: border-box,让padding和border被包含在设置的width范围内。你可以选择全局设置(更省心)或单独给导航栏设置:

方法1:全局设置(推荐)

在CSS最顶部添加,让所有元素都使用这个盒模型:

* {
  box-sizing: border-box;
}

方法2:单独给导航栏设置

直接修改.primary-navigation的CSS:

.primary-navigation {
  list-style: none;
  padding: 1rem;
  margin: 0;
  background: dodgerblue;
  width: 100%;
  border: 2px solid red;
  box-sizing: border-box; /* 新增这一行 */
}

修改后的完整CSS代码

@import url("https://fonts.googleapis.com/css2?family=Poppins&display=swap");
* {
  box-sizing: border-box;
}
body {
  margin: 0;
  font-family: "Poppins", sans-serif;
}

.flex {
  display: flex;
  gap: 2rem;
}

.primary-header {
  border: 2px solid blue;
  justify-content: center;
}

.primary-navigation {
  list-style: none;
  padding: 1rem;
  margin: 0;
  background: dodgerblue;
  width: 100%;
  border: 2px solid red;
}

.primary-navigation a {
  text-decoration: none;
  color: #ffffff;
}

.primary-navigation a:hover,
.primary-navigation a:focus {
  color: #afafaf;
}

修改后导航栏的总宽度会刚好填满父容器,右侧多余空间的问题就解决了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:35:26