如何用CSS实现汉堡菜单从“=”到“×”的切换并修复对齐问题
解决汉堡菜单切换为叉号的对齐问题
你的代码核心问题在于切换叉号时使用了固定的translate偏移值,没有基于容器中心定位,导致对齐偏差。下面是调整后的实现方案,能让菜单切换时完美对齐:
修改后的CSS代码
header { background-color: #000000; width: auto; height: 114px; display: flex; flex-direction: row; align-items: center; justify-content: space-between; padding: 0 40px; } .logo { width: auto; height: auto; } .hamburger { cursor: pointer; position: relative; /* 作为内部线条的定位容器 */ width: 44px; height: 44px; } .line { position: absolute; /* 绝对定位,精准控制位置 */ left: 0; right: 0; margin: 0 auto; /* 水平居中 */ width: 100%; height: 4px; background-color: #ffffff; border-radius: 10px; transition: all 0.3s ease; transform-origin: center; /* 旋转中心设为线条中点 */ } .line1 { top: 10px; /* 初始状态:上方线条 */ } .line2 { bottom: 10px; /* 初始状态:下方线条 */ } .hamburger.active .line1 { transform: rotate(45deg); /* 旋转成叉号的一条边 */ top: 20px; /* 移动到容器中心位置 */ } .hamburger.active .line2 { transform: rotate(-45deg); /* 旋转成叉号的另一条边 */ bottom: 20px; /* 移动到容器中心位置 */ }
关键调整说明
- 把
.hamburger设为相对定位,内部线条用绝对定位,精准控制每条线的初始和切换后的位置。 - 给线条设置
transform-origin: center,确保旋转时围绕自身中心点进行,避免偏移。 - 切换为叉号时,直接将两条线移动到容器中心再旋转,替代原来的固定
translate值,适配容器大小的同时保证对齐准确。
保持原HTML代码不变
<header> <div className="logo"> <img src={LogoSvg} alt="stan+vision logo" width="165px" height="24px" /> </div> <div role="button" className={`hamburger ${isActive ? "active" : ""}`} onClick={toggleMenu}> <div className="line line1"></div> <div className="line line2"></div> </div> <div> <button>Theme</button> </div> </header>
内容的提问来源于stack exchange,提问作者Frontastic DemoMail
相关产品推荐
相关产品推荐

