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

React+Tailwind CSS移动端导航菜单绝对定位无法完美居中的问题求助

React+Tailwind CSS移动端导航菜单绝对定位无法完美居中的问题求助

大家好,我正在React项目里用Tailwind CSS做导航菜单,现在遇到个小屏幕适配的问题——当在移动端触发菜单显示时,没法让菜单在header区域完美居中。

目前我临时用left-[15%]来定位菜单,但效果始终差一点,没法做到完全居中。我尝试了好几种不同的定位方式,都没得到理想的结果,想请各位帮忙看看我的代码哪里可以调整,实现菜单在小屏幕下完美居中的效果?

import { useState, useEffect } from "react";

export default function Header() {
  // States
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);
  const [menuon, setMenuOn] = useState(false);

  // Functions
  useEffect(() => {
    function handleResize() {
      setWindowWidth(window.innerWidth);
    }

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  function Menu() {
    setMenuOn(!menuon);
  }

  // SVGS
  const menusvg = (
    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
      <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 9h16.5m-16.5 6.75h16.5" />
    </svg>
  );

  return (
    <div className="p-14">
      {/*Menu Ternary for Screen Size*/}
      {windowWidth >= 640 ? (
        <div className="flex  items-center justify-between font-poppins text-lg gap-5">
            <h1>
                **
            </h1>
            <menu className="gap-5 z-[2] flex">
                <button>More Info</button>
                <button>Donate</button>
                <button>Email Us</button>
            </menu>
          
        </div>
      ) : (
        <div className="flex text-lg items-center justify-between  gap-4 ">

            <h1>
                **
            </h1>
            <button
                className={`${menuon ? 'bg-slate-400' : null} hover:bg-slate-500 hover:bg-opacity-35 transition-all p-2 bg-opacity-35 rounded-xl`}
                onClick={Menu}>
                {menusvg}
            </button>
            

          <menu className={`gap-7 ${menuon ? 'opacity-100 pointer-events-auto translate-y-40 ' : 'pointer-events-none   opacity-0'}  whitespace-nowrap right-[22%] p-4 pr-24 pl-24 bg-white duration-500 z-10 will-change-transform  transition-all rounded-xl absolute flex flex-col`}>
            <button>More Info</button>
            <button>Donate</button>
            <button>Email Us</button>
            <hr />
          </menu>
        </div>
      )}
    </div>
  );
}

备注:内容来源于stack exchange,提问作者Patrick Long

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:13:01