导航栏的嵌套 Flexbox

问题描述 投票:0回答:1

我一直在努力使用 React 制作下拉导航栏,类似于下图 - enter image description here

我的代码-

NavBar.jsx

import React, { useState } from 'react'
import './NavBar.css'


const NavBar = () => {
    const [openDropDown,setOpenDropDown] = useState(null)

    const toggleDropDown = (menu) =>{
        setOpenDropDown(openDropDown === menu ? null : menu)
    }
  return (
    <>
    <nav className = 'navbar'>
        <img className = 'logo' src = '../../images/logo.svg'/>
        <div className='list-container'>
        <ul className  = 'left-list'>
            <li className = 'navbar-items' onMouseEnter={() => toggleDropDown('features')} onMouseLeave={() => toggleDropDown()}>
                Features
                {openDropDown === 'features' && 
                <ul className='dropdown-list'>
                    <li className='features-items'>Todo List</li>
                    <li className='features-items'>Calender</li>
                    <li className='features-items'>Reminders</li>
                    <li className='features-items'>Planning</li>
                </ul>}
            </li>
            <li className = 'navbar-items' onMouseEnter={() => toggleDropDown('company')} onMouseLeave={() => toggleDropDown()}>
                Company
                {openDropDown === 'company' &&
                <ul className='dropdown-list'>
                    <li className='company-items'>History</li>
                    <li className='company-items'>Our Team</li>
                    <li className='company-items'>Blog</li>
                </ul>} 
            </li>
            <li className = 'navbar-items'>Careers</li>
            <li className = 'navbar-items'>About</li>
        </ul>

        <ul className = 'right-list'>
            <li className = 'navbar-items'>Login</li>
            <li className = 'navbar-items'>Register</li>
        </ul> 
        </div>
    </nav>
    </>
  )
}

export default NavBar

导航栏.css

*{
    box-sizing: border-box;
    margin: 0;
    padding : 0;
}

.navbar{
    display : flex;
    align-items: center;
    gap: 30px;
}
.list-container{
    display: flex;
    justify-content: space-around;
}
.left-list{
    display: flex;
}
.right-list{
    display: flex;
}
.navbar-items{
    margin : 20px;
}
.logo{
    margin-left: 50px;
    height: 20px;
    width: 50px;
}

我有一个导航栏类,其中有一个图像(徽标)和一个 div(包含两个列表)。我已将 flex 应用于 .navbar,它似乎按预期工作。 我尝试将 flex 与 justify-content: space around 一起应用于 .list-container,但子元素仍保留在同一位置。 我应该在代码中更改什么以使其类似于上图?

css reactjs flexbox navbar
1个回答
0
投票

如果您的目标是让登录和注册位于右侧,其余导航位于左侧,您可以像这样调整 CSS:

list-container {
  display: flex;
  justify-content: space-between;
  flex-grow: 1;
}

如果其他部分是您的问题,请澄清您的问题。

资源:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

© www.soinside.com 2019 - 2024. All rights reserved.