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

如何在不添加padding、不增大背景的前提下实现导航栏内容居中

解决方案

只需调整768px以上断点的nav ul样式即可,不会改变导航栏背景尺寸,也不需要额外添加padding:

  • 删除原有nav ul下的float: right、margin-right: 40px、text-align: right属性
  • 新增flex布局相关属性实现内部内容水平垂直居中,flex布局只会调整容器内子元素的位置,不会修改容器本身的宽高参数

修改后的完整CSS代码如下:

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

body {
    font-family: Arial, Helvetica, sans-serif;
}

nav ul li a {
    font-size: 26px;
    color: white;
}

ul {
    position: fixed;
    width: 100%;
    height: 50vh;
    background: #091624;
    top: auto;
    left: auto;
    text-align: center;
}

nav ul li {
    display: block;
    margin: 20px 0;
    line-height: normal;
}

a.content,
a:hover {
    background: #1b9bff;
    transition: .5s;
}

@media screen and (min-width: 768px) {
    nav {
        height: 80px;
        width: 100%;
    }
    nav ul {
        position: fixed;
        height: 60px;
        width: 100%;
        /* flex布局实现内部内容居中 */
        display: flex;
        justify-content: center;
        align-items: center;
    }
    nav ul li {
        display: inline-block;
        line-height: 80px;
        margin: 0 5px;
    }
    nav ul li a {
        color: white;
        font-size: 17px;
        padding: 7px 13px;
        border-radius: 3px;
    }
}

HTML代码不需要做任何修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 19:54:03