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

React使用styled-components设置导航栏样式异常问题求助

错误点整理

  • NavbarContainer 中 z-index: 1' 错误使用单引号代替分号,导致后续所有样式规则失效,直接引发排版错位、对齐异常
  • MobileIcon 规则存在三处错误:top: o 把数字0写为字母o、transfrom 拼写错误(正确为transform)、图标颜色设为黑色#000和导航栏黑色背景重合,所以完全看不到菜单图标
  • NavMenu 中 align-itens 拼写错误,正确为align-items,导致菜单项对齐异常
  • NavLinks 中 &.active 错误使用HTML转义字符,正确应为&.active,导致激活状态样式不生效
  • 冗余导入测试包语句import { findByLabelText } from '@testing-library/dom'无意义可删除

修正后代码

import styled from 'styled-components'
import {Link as LinkR} from 'react-router-dom'
import {Link as LinkS} from 'react-scroll'

export const Nav = styled.nav`
    background: #000;
    height: 80px; 
    /*margin-top: -80px; */
    display: flex;
    justify-content: center; 
    align-items: center;
    font-size: 1rem; 
    position: sticky; 
    top: 0;
    z-index: 1;

    @media screen and (max-width: 960px) {
        transition: 0.8s all ease;
    }
`

export const NavbarContainer = styled.div`
    display: flex;
    justify-content: space-between;
    height: 80px;
    z-index: 1;
    width: 100%;
    padding: 0 24px;
    max-width: 1100px;
`

export const NavLogo = styled(LinkR)`
    color: red;
    justify-self: flex-start;
    cursor: pointer; 
    font-size: 1.5rem;
    display: flex;
    align-items: center;
    margin-left: 24px;
    font-weight: bold;
    text-decoration: none;
`;

export const MobileIcon = styled.div`
    display:none;

    @media screen and (max-width: 768px) {
        display: block;
        position: absolute;
        top: 0;
        right: 0;
        transform: translate(-100%, 60%);
        font-size: 1.8rem;
        cursor: pointer;
        color: #fff; 
    }
`
export const NavMenu = styled.ul`
    display: flex;
    align-items: center;
    list-style: none;
    text-align: center;
    margin-right: -22px;

    @media screen and (max-width: 768px) {
        display: none;
    }
`

export const NavItem = styled.li`
    height: 80px;
`

export const NavLinks = styled(LinkS)`
    color: #fff;
    display: flex;
    align-items: center;
    text-decoration: none;
    padding: 0 1rem;
    height: 100%;
    cursor: pointer;

    &.active {
        border-bottom: 3px solid #01bf71;
    }
`

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:00:03