Bootstrap导航栏过渡动画失效问题排查与解决求助
Cause
Bootstrap 5's default navbar collapse transition animates the height property, which can fail to work smoothly with flexbox-based content (like .navbar-nav). The automatic height calculation doesn't always register correctly, leading to instant show/hide instead of a smooth transition.
Fix
Add custom CSS to use max-height for the transition, which handles flex content more reliably:
.navbar-collapse.collapsing { max-height: 0; overflow: hidden; transition: max-height 0.35s ease-in-out; } .navbar-collapse.show { max-height: 100vh; /* Use a value larger than your navbar's maximum possible height */ }
Corrected Full Code
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap demo</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <style> .navbar-collapse.collapsing { max-height: 0; overflow: hidden; transition: max-height 0.35s ease-in-out; } .navbar-collapse.show { max-height: 100vh; } </style> </head> <body> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link active" aria-current="page" href="#">Home</a> <a class="nav-link" href="#">Features</a> <a class="nav-link" href="#">Pricing</a> <a class="nav-link disabled">Disabled</a> </div> </div> </div> </nav> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> </body> </html>
Explanation
By animating max-height instead of height, we avoid issues with flexbox height calculation. Setting max-height: 0 during collapse and 100vh (viewport height) when expanded ensures the transition works smoothly regardless of the navbar content's actual height.
内容的提问来源于stack exchange,提问作者user25838867
相关产品推荐
相关产品推荐

