Bootstrap 4中如何让导航栏内链接高度适配导航栏可用高度?
Hey there! Let's break down why your current navbar link isn't filling the full height of the navbar, and how to fix it easily.
Why Your Current Code Isn't Working
- The plain
<a>tag is an inline element by default. Inline elements only take up as much vertical space as their text content—they won't automatically stretch to match the navbar's height. - You're not using Bootstrap's built-in navigation classes. The
navbarcomponent expects specific structure (likenavbar-nav,nav-link) that handles vertical alignment, padding, and height out of the box.
Fix 1: Use Bootstrap's Native Navbar Classes (Recommended)
This is the cleanest approach because it leverages Bootstrap's pre-built styles, ensuring consistency and responsiveness. Here's the adjusted code:
<nav class="navbar navbar-light bg-light"> <span class="navbar-brand mb-0 h1">Brand</span> <div class="navbar-nav"> <a class="nav-link" href="#">I wanna grow</a> </div> </nav>
- Wrap your link in a
<div class="navbar-nav">to group it properly with other nav items (if you add more later). - The
nav-linkclass does all the heavy lifting: it adds vertical padding, sets the link to a block-level element, and ensures it fills the full height of the navbar while keeping text centered vertically.
Fix 2: Custom CSS (If You Want to Avoid Bootstrap's Nav Components)
If you prefer a custom solution, you can manually style the link to stretch. Here's how:
<nav class="navbar navbar-light bg-light d-flex align-items-stretch"> <span class="navbar-brand mb-0 h1">Brand</span> <a href="#" class="navbar-stretched-link">I wanna grow</a> </nav> <style> .navbar-stretched-link { display: flex; align-items: center; /* Centers text vertically */ height: 100%; padding: 0 1rem; /* Match Bootstrap's default spacing */ text-decoration: none; color: inherit; } </style>
- We add
d-flex align-items-stretchto the navbar to make its children stretch vertically. - The custom
.navbar-stretched-linkclass makes the<a>a flex element (to center text), setsheight: 100%to fill the navbar, and adds padding for a polished look.
Either method will get your link filling the full navbar height—Bootstrap's native classes are the best choice for long-term maintainability!
内容的提问来源于stack exchange,提问作者amedina
相关产品推荐
相关产品推荐

