React导航栏选中列表项居中的Flexbox CSS实现问询
Got it, let's build that centered active nav item with smooth transitions in React—here's a complete solution tailored to your setup using a <ul> and Flexbox:
Step 1: React Component Implementation
First, we'll create the nav component with state to track the active item, refs to access DOM elements, and logic to calculate the offset needed to center the active list item.
import { useState, useRef, useEffect } from 'react'; import './Navbar.css'; const Navbar = () => { // Track the index of the active nav item const [activeIndex, setActiveIndex] = useState(0); // Refs to access the nav container and individual list items const navContainerRef = useRef(null); const navItemRefs = useRef([]); // Handle click to set active item const handleNavClick = (index) => { setActiveIndex(index); }; // Calculate and apply offset to center active item when it changes useEffect(() => { if (!navContainerRef.current || !navItemRefs.current[activeIndex]) return; const container = navContainerRef.current; const activeItem = navItemRefs.current[activeIndex]; // Find the center point of the container and the active item const containerCenter = container.offsetWidth / 2; const itemCenter = activeItem.offsetLeft + activeItem.offsetWidth / 2; // Calculate how much to shift the nav list left/right const offset = itemCenter - containerCenter; // Apply smooth transform to the list container.querySelector('ul').style.transform = `translateX(-${offset}px)`; }, [activeIndex]); const navItems = ['One', 'Two', 'Three', 'Four']; return ( <div className="navbar-container" ref={navContainerRef}> <ul className="nav-list"> {navItems.map((item, index) => ( <li key={index} ref={(el) => (navItemRefs.current[index] = el)} className={`nav-item ${index === activeIndex ? 'active' : ''}`} onClick={() => handleNavClick(index)} > {item} </li> ))} </ul> </div> ); }; export default Navbar;
Step 2: CSS Styling
Next, we'll use Flexbox for layout, add overflow handling, and set up smooth transitions for both the nav list movement and active item highlights.
/* Navbar container - hides overflow so only centered items are visible */ .navbar-container { width: 100%; max-width: 800px; /* Adjust this to fit your layout */ margin: 0 auto; overflow: hidden; border-bottom: 1px solid #e0e0e0; } /* Flex layout for the nav list */ .nav-list { display: flex; list-style: none; padding: 0; margin: 0; /* Smooth transition for the list's position */ transition: transform 0.3s ease-in-out; } /* Individual nav items - prevent shrinking so widths stay consistent */ .nav-item { flex-shrink: 0; padding: 1rem 1.5rem; cursor: pointer; color: #333; transition: color 0.2s ease; } /* Highlight active item */ .nav-item.active { color: #2563eb; font-weight: 600; } /* Optional: Add an underline indicator for active item */ .nav-item.active::after { content: ''; display: block; width: 70%; height: 2px; background-color: #2563eb; margin: 0.3rem auto 0; transition: width 0.3s ease; }
How It All Comes Together
- Centering Logic: The
useEffecthook calculates the position of the active item relative to the container's center, then shifts the entire<ul>usingtransform: translateX()to center the active item. - Smooth Transitions: The
transitionproperty on.nav-listmakes the shift animation smooth, while the active item's color and underline also get subtle transitions for polish. - Flexbox Layout: Ensures the list items stay horizontal and don't shrink unexpectedly, keeping the layout consistent.
Extra Customizations
- Adjust the
transitionduration (e.g.,0.4s) or easing function (e.g.,cubic-bezier(0.4, 0, 0.2, 1)) to match your design's feel. - Modify the
.navbar-containerwidth or add media queries to make the nav responsive on mobile. - Change the active item's color or indicator style to fit your brand.
内容的提问来源于stack exchange,提问作者Adam Olsson
相关产品推荐
相关产品推荐

