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

使用Flexbox制作导航栏遇问题:元素无法横向排列而堆叠

导航栏元素堆叠问题修复

问题根源

  1. 类选择器语法错误:CSS中.nav_links类选择器漏写了前缀圆点,导致nav_links li规则完全无效,<li>保持默认块级显示,自然堆叠。
  2. 全局样式冲突:*选择器强制给所有元素设置background-color,覆盖了header的渐变背景,同时干扰布局视觉表现。
  3. 渐变语法错误:-moz-linear-gradient缺少颜色参数之间的逗号,且未添加标准linear-gradient属性,导致渐变不生效。

修正后的代码

CSS代码

@import url('https://fonts.googleapis.com/css2?family=Roboto+Slab&display=swap');

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    text-decoration: none;
}

li, a, button {
    font-family: 'Roboto Slab', serif;
    font-weight: 400;
    font-size: 20px;
    text-decoration: none;
    color: #333;
}

header {
    background: linear-gradient(#0000ff, #A2d0c1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 12%;
}

.nav_links {
    list-style: none;
    display: flex;
    gap: 20px;
}

HTML代码

<html>
    <head>
            <link rel="stylesheet" href="menustyle.css">
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <header>
            <img src="Adidas_Logo.svg.png" alt="logo" style="width: 100px;">
            <nav>
                <ul class="nav_links">
                    <li><a href="#">Products</a></li>
                    <li><a href="#">Categories</a></li>
                    <li><a href="#">Notifications</a></li>
                </ul>
            </nav>
            <a href="#" class="cta"><button>Card</button></a>
        </header>
    </body>
</html>

额外优化说明

  • 给*选择器添加margin: 0和padding: 0,清除浏览器默认样式,避免布局偏移。
  • 给文字添加color属性,防止与背景色融合看不清。
  • 用display: flex实现导航项横向排列,比inline-block更易控制间距和对齐。
  • 添加viewport meta标签,适配移动端布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:45:39