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

React中导航文本为何显示在图片下方而非同行?悬停下划线为何不生效?

解决React导航栏布局与悬停动画问题

看起来你遇到了两个典型的布局和CSS动画问题,我来帮你一步步搞定它们:


问题1:Logo与导航链接无法同行排列

原因分析

你的Wrapper容器没设置display: flex,导致LeftSide、Center、RightSide这三个子元素默认以块级元素垂直排列。另外,Wrapper的padding属性里有个小错误(1.5 rem多了空格,应该是1.5rem),可能会影响内边距计算。

修复方案

修改NavBar.js中的Wrapper样式:

const Wrapper = styled.div`
  width: 100%;
  height: 10rem;
  /* 添加flex布局,让子元素横向排列 */
  display: flex;
  align-items: center;
  /* 修正空格错误 */
  padding: 0 1.5rem;
  /* 可选:让三个区域合理分布空间,可根据需求调整 */
  justify-content: space-between;
  transition: background-color .5s ease;
  z-index: 9999;
  border-bottom: 2px solid rgba(255,255,255,.05);
  margin-left: 50px;
  margin-right: 50px;
`;

加上display: flex后,Logo和导航链接就能在同一行显示了,justify-content: space-between能让左右区域自动分开,中间内容居中,你也可以换成justify-content: flex-start让所有元素靠左对齐。


问题2:鼠标悬停下划线动画不生效

原因分析

有两个关键问题:

  1. 伪元素::after没设置position: absolute,它默认是inline元素,没法通过transform实现缩放动画,也不能正确定位在文本下方。
  2. transition属性语法错误,少了冒号(transition transform .5s ease应该是transition: transform .5s ease)。

另外你设置了Link的color: black,所以默认的蓝色链接样式被覆盖了,这是正常的;如果想保留默认蓝色,删掉这个颜色设置就行。

修复方案

修改NavLinks.js中的Link样式:

const Link = styled.a`
  text-decoration: none;
  color: black; /* 如果需要默认蓝色,可删除这一行 */
  font-size: 1.6rem;
  margin: 0 2rem;
  position: relative;

  &:hover{
    color: rgb(24, 23, 23); /* 可选:hover时调整文字颜色 */
  }

  &::after {
    content: '';
    width: 100%;
    height: 2px;
    background-color: black;
    left: 0;
    bottom: -3px;
    /* 添加绝对定位,让伪元素基于父元素定位 */
    position: absolute;
    transform: scaleX(0);
    transform-origin: left;
    /* 修正transition语法 */
    transition: transform .5s ease;
  }

  &:hover::after{
    transform: scaleX(1);
  }
`;

额外小细节:Logo组件函数定义规范

你的Logo.js中函数定义缺少function关键字,虽然部分环境能运行,但标准写法应该是:

// 创建logo函数
function Logo(props) {
  return(
    <LogoWrapper>
      <LogoImg><img src={USLogo} alt="US. logo"/></LogoImg>
      <LogoText>US.</LogoText>
    </LogoWrapper>
  );
}

做完这些修改后,导航栏应该能正常横向排列,悬停时也会出现从左到右的下划线动画了。如果还有布局细节需要调整,可以根据需求微调flex属性或者动画参数~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:34:06