移动端Bootstrap导航栏默认未折叠问题求助(Drupal 8+Bootstrap3.0)
Hey there! Let's work through getting your Bootstrap 3 navbar to collapse by default like you want it to. I took a look at your code and spotted a couple of key issues that are blocking the functionality—let's break them down and fix 'em:
1. Missing Collapse Container for Your Menu
Bootstrap's collapse feature relies on wrapping your navigation links in a container with the classes collapse navbar-collapse, and this container must have the exact ID that matches your toggle button's data-target (yours is #main-navigation). Right now, your page.primary_menu is sitting directly in the <nav> tag without this wrapper, so the toggle button has no idea what to collapse!
2. Broken Grid Structure
You nested a .row directly inside another .row, which violates Bootstrap's grid rules (rows should only go inside containers or columns, not other rows). This messes up responsive breakpoints and prevents the navbar from switching to collapsed mode at the right screen size.
Corrected Code
Here's the revised version of your header/navbar code with all fixes applied:
<!-- Header and Navbar --> <header class="main-header"> <div class="container"> <div class="row"> <div class="col-sm-4 col-md-3"> {% if page.header %} {{ page.header }} {% endif %} </div> <div class="col-sm-8 col-md-9"> <!-- Replaced nested row with proper column --> <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <!-- Wrap primary menu in required collapse container --> <div id="main-navigation" class="collapse navbar-collapse"> {% if page.primary_menu %} {{ page.primary_menu }} {% endif %} </div> </nav> </div> </div> </div> </header> <!--End Header & Navbar -->
Quick Additional Checks
Don't skip these—they're easy to miss but critical:
- Make sure Bootstrap 3's CSS is properly loaded in your Drupal theme (usually via your
.info.ymlfile or a template) - Confirm you've included jQuery (required for Bootstrap's JavaScript plugins) and Bootstrap 3's full JavaScript file (which includes the collapse component)
Once you update your code and double-check those dependencies, your navbar should collapse by default on mobile screens and expand when you tap the toggle button. If you hit any other bumps, feel free to ask!
内容的提问来源于stack exchange,提问作者Bo Maxwell Stevens

