Tailwind CSS按钮切换元素显隐时过渡动画不生效问题
Hey Jamie, let's figure out why that slide-in transition works when tweaking styles in dev tools but not when toggling the show state with a button—your manual test gives us a key clue here!
The Core Issue
Looking at your classNames logic, you're only adding the transition-all duration-700 classes when show is true. For CSS transitions to animate property changes, the element needs to have transition properties applied both before and after the state shift. When show is false, your element has no transition classes at all, so when you toggle to true, there's no transition setup to animate the right value change—it just jumps straight to the new position.
The Fix
Move the transition-related classes into the shared part of your className string, so they're always present regardless of the show state. You only need to toggle the right and margin values based on show:
<div className={classNames( "top-0 transition-all duration-700 absolute md:fixed w-screen md:w-40 bg-default overflow-y-auto flex", show ? "right-[0px] mt-0" : "-right-[330px] mt-14 md:left-0" )} ></div>
What Changed:
transition-all duration-700is now in the base class list, so it's active whether the element is hidden or visible.- Conditional classes are simplified to only the properties that actually change:
right-[0px] mt-0when visible,-right-[330px] mt-14 md:left-0when hidden. - Cleaned up the structure to make which classes are permanent vs. conditional much clearer.
Quick Sanity Checks
- State Updates: Double-check that your
showstate is updating correctly (e.g., using React'suseStatewithout stale closures). Since dev tools work, this is likely fine, but it's worth a quick verify. - No Overrides: Use dev tools' computed styles tab to make sure no other styles are unexpectedly overriding the
rightproperty when the state toggles.
This should make the transition fire smoothly when you click the button, just like it does when you tweak styles manually!
内容的提问来源于stack exchange,提问作者Jamie Garcia

