首页 > 解决方案 > 导航栏样式活动下划线

问题描述

我有一个导航栏,当用户将鼠标悬停在链接上时,它会为下划线设置动画。我正在尝试添加 css,以便活动导航栏具有永久下划线。

我的代码

<Navbar className="navbar-expand-sm navbar-toggleable-sm" light>
                <Container id="ContainerGrnH">
            <NavbarToggler onClick={this.toggleNavbar} className="mr-2" />
                    <Collapse className="d-sm-inline-flex flex-sm-row-reverse" isOpen={!this.state.collapsed} navbar>
            <div class="topnav">
              <ul className="navbar-nav flex-grow">
                <NavItem>
                  <NavLink tag={Link} className="text-white"  to="/home">HOME <div className="underline"></div></NavLink>
                </NavItem>
                <NavItem>
                    <NavLink tag={Link} className="text-white" to="/people-profiles">PEOPLE PROFILES<div className="underline"></div></NavLink>
                </NavItem>
                <NavItem>
                    <NavLink tag={Link} className="text-white" to="/Role-types">ROLE TYPES<div className="underline"></div></NavLink>
                </NavItem>
                <NavItem>
                    <NavLink tag={Link} className="text-white" to="/support">SUPPORT<div className="underline"></div></NavLink>
                </NavItem>
                <NavItem>
                    <NavLink tag={Link} className="text-white" id="contactushead" to="/contact-us">CONTACT US<div className="underline"></div></NavLink>
                </NavItem>
                </ul>
                </div>
            </Collapse>
          </Container>
            </Navbar> 
.topnav ul a {
    color: #ffffff;
    text-decoration: none;
    padding: 10px;
    transition: color 0.5s;
}
.topnav ul li .underline {
    height: 3px;
    background-color: transparent;
    width: 0%;
    transition: width 0.2s, background-color 0.5s;
    margin: 0 auto;
}

.topnav ul li.active-link .underline {
    width: 100%;
    background-color: white;
}

.topnav ul li:hover .underline {
    background-color: white;
    width: 100%;
}

.topnav ul li:hover a {
}

.topnav ul li:active a {
    transition: none;
    color: rgba(255,255,255,0.76);
}

.topnav ul li:active .underline {
    transition: none;
    background-color: rgba(255,255,255,0.76);
}

这很可能是一个小错误,但我已经玩了一段时间,似乎找不到很多解决方案。

在此处输入图像描述

正如您从图像中看到的那样,由于已选择 home,因此应在 home 一词下划线。

标签: cssreactjsnavbarnav

解决方案


你在使用 react-router-dom 的 NavLink 吗?

如果是这样,实际上有一个 activeClassName 道具可用于识别当前正在访问的路线。

<NavLink tag={Link} className="text-white" exact activeClassName="underline" to="/people-profiles">PEOPLE PROFILES</NavLink>

在你的 CSS 中

.underline {
 border-bottom-width: 2px;
}

不要忘记在 NavLink 的道具中添加精确以与路线正确匹配。

在这里阅读更多: https ://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md


推荐阅读