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

CSS flex导航栏移动端溢出滑至内容下方,桌面端正常如何修复

根因定位
  • 属性错配的硬bug:把position: sticky同时绑在body和.nav-links上,还遗漏了sticky定位必须搭配的top偏移值,定位逻辑从根源上就是失效的。更明显的语法错误是写了max-width: -100%这种负宽度声明,浏览器解析时直接触发布局计算异常,位置偏移是必然结果。
  • 缺失移动端适配:.nav-links硬编码了50%宽度、19px粗体字大小,移动端屏幕本身宽度有限,横向排列的导航项总宽度超过容器可用空间时,flex布局的空间不足,导航块直接被挤出顶部文档流,偏移到页面内容下方。
  • 层级设置不合理:导航容器没有设置全局最高z-index,滚动时容易被后续页面内容覆盖,进一步放大“导航跑到内容下面”的视觉异常。
可直接落地的修复方案
  1. 先把错配的属性拆分到正确的元素上:删掉所有负宽度声明,把sticky定位迁移到nav本体,补上top:0的必填偏移值,给nav设置足够高的层级保证永远在最上层
  2. 给768px以下的移动端加媒体查询,把原本横向摊开的导航链接改成侧边折叠模式,默认藏在屏幕外,靠汉堡按钮控制滑出,避免窄屏下导航项硬挤导致的布局错位
  3. 清除body的默认外边距,减少不必要的布局偏移计算

修正后的完整CSS代码

body {
    max-width: 100%;
    overflow-x: hidden;
    margin: 0;
}

nav{
    display: flex;
    justify-content: space-around;
    align-items: center;
    min-height: 8vh;
    background-color: rgba(99, 99, 99, 0.404);
    font-family: 'poppins', sans-serif;
    overflow-x: hidden;
    /* sticky定位挪到导航本体上,补全必填属性 */
    position: sticky;
    top: 0;
    z-index: 999;
}

.logo{
    color: #ffff;
    text-transform: uppercase;
    letter-spacing: 5px;
    font-size: 22px;
}

.nav-links{
    display: flex;
    justify-content: space-around;
    width: 50%;
    z-index: 1;
}

.nav-links li{
    list-style: none;
}

.nav-links a{
    color: rgb(255, 255, 255);
    text-decoration: none;
    letter-spacing: 2px;
    font-weight: bold;
    font-size: 19px;
}

.burger {
    display: none;
    cursor: pointer;
}

.burger div {
    width: 25px;
    height: 2px;
    background-color: #fff;
    margin: 5px;
    transition: all 0.3s ease;
}

/* 新增移动端适配断点 */
@media screen and (max-width: 768px) {
    .nav-links {
        position: absolute;
        right: 0;
        height: 92vh;
        top: 8vh;
        background-color: rgba(99, 99, 99, 0.95);
        flex-direction: column;
        align-items: center;
        width: 40%;
        transform: translateX(100%);
        transition: transform 0.3s ease-in;
    }
    .burger {
        display: block;
    }
    /* 配合基础JS逻辑,给元素加这个类即可实现导航滑出效果 */
    .nav-active {
        transform: translateX(0);
    }
}

原代码中把sticky绑定在body和子元素上的写法,就算桌面端看起来正常,也是靠浏览器的容错渲染撑着的,遇到移动端尺寸变化就会立刻暴露位置偏移的问题。

内容的提问来源于stack exchange,提问作者L Y N X

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 01:45:05