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

如何实现4列布局、文字居中且可加border-bottom的导航栏?

导航栏布局修复方案

需求说明

实现4列等宽的导航栏布局,每个导航项为盒子形态,内部文字水平垂直居中,且支持为指定导航项添加底部边框样式。

修改后的完整代码

HTML代码

<body>
    <header>
        <a class="logo" href="/">filmfestwilsdruff.de</a>
        <nav>
            <ul class="nav__links">
                <li><a href="#" class="active">Home</a></li>
                <li><a href="#">blabla</a></li>
                <li><a href="#">blabla</a></li>
                <li><a href="#">blablabla</a></li>
            </ul>
        </nav>
        <a class="cta" href="#">Contact</a>
    </header>
</body>

CSS代码

header {
    display: flex;
    justify-content: space-between;
    align-items: stretch;
    width: 100%;
    height: 70px;
    padding: 0 10%;
    background-color: #EFEFEF;
    box-sizing: border-box;
}

.logo {
    cursor: pointer;
    text-decoration: none;
    color: #707070;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    display: flex;
    align-items: center;
}

.nav__links a,
.cta,
.overlay__content a {
    font-family: "Montserrat", sans-serif;
    font-weight: 500;
    color: #707070;
    text-decoration: none;
}

.nav__links {
    list-style: none;
    display: flex;
    width: 60%;
    padding: 0;
    margin: 0;
}

.nav__links li {
    flex: 1;
    display: flex;
}

.nav__links li a {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid black;
    box-sizing: border-box;
}

.nav__links li a.active {
    border-bottom: 8px solid green;
}

.cta {
    display: flex;
    align-items: center;
    padding: 9px 25px;
    background-color: rgba(0, 136, 169, 1);
    border: none;
    border-radius: 50px;
    cursor: pointer;
    transition: background-color 0.3s ease 0s;
}

关键改动说明

  • 调整header的align-items为stretch,让导航区域子元素自动撑满header高度,保证导航项盒子与header高度一致
  • 给.nav__links设置宽度,内部li使用flex:1实现4列等宽均分布局
  • 将导航项<a>设为flex容器,通过justify-content: center和align-items: center实现文字水平垂直居中,同时撑满父级空间
  • 将原ID选择器#active改为类选择器.active,提升样式复用性
  • 给涉及尺寸的元素添加box-sizing: border-box,避免边框、内边距撑开盒子,保证布局可控
  • 给logo和cta添加垂直居中样式,统一整体视觉效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:14:54