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

为何left:50%;transform:translateX(-50%)无法居中我的Logo?

问题原因分析

你的header采用flex布局,在屏幕宽度≤900px时,虽隐藏了nav,但#bars(左侧汉堡按钮)和#pin(右侧图标)仍作为flex子元素占据左右空间。此时给logo设置position: relative; left:50%; transform: translateX(-50%),偏移是基于logo在flex流中的初始位置(#bars右侧)计算的,而非整个header的宽度中心,因此会出现偏离。

修复方案

利用flex布局特性实现logo居中,同时保留左右按钮:

  • 将#bars和#pin设为绝对定位,脱离flex流,避免占用flex容器空间
  • 给header添加justify-content: center,让logo在flex容器中自动居中
修改后的代码

CSS部分

#bars {
  display: none;
}

header {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding-top: 7px;
  padding-bottom: 7px;
  height: 26px;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
}

#logo {
  width: 12%;
  margin-left: 3%;
}

#pin {
  margin-right: 3%;
  width: 2%;
  margin-left: auto;
}

nav a {
  margin-left: 20px;
  margin-right: 20px;
}

nav {
  margin: auto;
}

@media screen and (max-width: 900px) {
  nav a, nav {
    display: none;
  }
  #bars {
    display: block;
    color: white;
    position: absolute;
    left: 3%;
  }
  #pin {
    position: absolute;
    right: 3%;
    margin-left: 0;
  }
  header {
    justify-content: center;
  }
  header #logo {
    margin-left: 0;
    width: 15%;
    /* 移除导致偏移的定位属性 */
    left: auto;
    position: static;
    transform: none;
  }
}

HTML部分(无需修改)

<header>
  <i class="fa-solid fa-bars" id="bars"></i>
  <img src="logo.svg" id="logo">
  <nav>
    <a href="index.html">Accueil</a>
    <a href="nosproduits.html">Nos produits</a>
    <a href="apropos.html">À propos</a>
    <a href="contact.html">Contact</a>
  </nav>
  <a id="pin" href="#"><img src="pin.svg"> </a>
</header>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:15:49