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

如何使用HTML/CSS实现logo居左、菜单居中的同排头部布局

问题核心原因

布局错位主要是以下几个代码问题导致的:

  • 外层导航容器.navigation没有设置弹性布局,两个子元素(logo、菜单容器)默认是块级元素,自动换行
  • CSS选择器匹配错误:HTML里header的id是header-center,但你写了类选择器.header-center,样式完全没生效
  • 使用了不存在的CSS属性:float: center没有任何效果
  • 菜单ul没设置横向排列,默认是纵向堆叠
  • 无效样式:#header选择器在你的HTML里不存在,额外设置的padding-top:695px还会把页面撑出异常间距
  • 链接边距过大:.header a设置的margin:70px会导致元素溢出容器

修正后的完整CSS代码

@charset "utf-8";

@font-face{
    font-family: 'nagoda';
    src: url('Nagoda.woff') format('woff'),
         url('Nagoda.otf') format('otf'),
         url('Nagoda.ttf') format('ttf');
    font-weight: normal;
    font-style: normal;
}

* {
    box-sizing: border-box;
    scroll-behavior: smooth;
    margin: 0;
    padding: 0;
}

/* 外层导航容器设为flex,实现子元素同行排列 */
.navigation {
    display: flex;
    align-items: center;
    padding: 25px 54px;
    width: 100%;
}

#logo_header{
    height: 110px;
    width: 110px;
}

/* 菜单容器占满剩余宽度,方便内容居中 */
.header {
    flex: 1;
}

/* 修正id选择器,设置菜单横向排列居中 */
#header-center {
    display: flex; 
    justify-content: center;
    width: 100%;
}

#menu{
    font-family: 'nagoda';
    font-size: 25px;
    list-style: none;
    display: flex;
    gap: 40px; /* 可自行调整菜单项间距 */
    align-items: center;
}

.header a {
    color: #383838;
    padding: 12px;
    text-decoration: none;
    font-size: 25px; 
    line-height: 15px;
    border-radius: 5px;
}

.header a:hover {
    background-color: #ed1c24;
    color: white;
}

.header a.active {
    background-color: #ed1c24;
    color: white;
}

li {
    line-height: normal;
}

@media screen and (max-width: 800px) {
    .navigation {
        flex-direction: column;
        gap: 20px;
    }
    #menu {
        flex-direction: column;
        gap: 15px;
    }
    .header a {
      display: block;
      text-align: center;
    }
}

body {
    background-image: url(Image_bg1.png);
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: local;
    background-size: cover;
    min-height: 695px;
    width: 100%;
}

效果说明

修改后可实现:

  • 桌面端logo居左,导航菜单整体水平居中,两者在同一行垂直对齐
  • 移动端自适应堆叠,菜单纵向排列
  • 移除了所有无效冲突样式,避免布局异常

内容的提问来源于stack exchange,提问作者Romain M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:45:03